MCP 服务器发布工具定义并执行工具调用。Agents API 发现这些工具,向服务器发起调用,并将结果返回给智能体。您的应用无需逐一处理这些调用。
请根据哪些位置能够访问服务器,选择从哪里发起连接。
| 连接方式 |
发起连接的位置 |
是否需要环境 |
HTTP,使用 connection_origin: "service"(默认) |
OpenAI |
否 |
HTTP,使用 connection_origin: "environment" |
您的会话环境 |
是 |
| stdio |
您的会话环境中的进程 |
是 |
将 HTTP MCP 服务器添加到 agent.tools。OpenAI 必须能够访问该服务器。无论是否配置了会话环境,都可以使用这种连接方式。
例如,OpenAI 文档 MCP 服务器允许匿名访问。
12345678910{
"type": "mcp",
"server_label": "openai_docs",
"transport": {
"type": "http",
"server_url": "https://developers.openai.com/mcp"
},
"connection_origin": "service",
"required": true
}
执行器从会话环境发起 MCP 连接。如果服务器位于专用网络中,或者您需要使用安装在会话环境中的软件,请使用这种连接方式。
将会话的 environment.type 设置为 self_hosted 或 openai_hosted。如果使用自托管环境,请在智能体使用工具之前连接执行器。
如果服务器已在运行,请使用 HTTP。将以下配置项添加到 agent.tools,并将其中的 URL 替换为您的环境可以访问的地址。
12345678910{
"type": "mcp",
"server_label": "internal_search",
"transport": {
"type": "http",
"server_url": "https://mcp.internal.example.com/search"
},
"connection_origin": "environment",
"required": true
}
在此配置中,localhost URL 指向会话环境。如果省略 connection_origin,则由 OpenAI 发起连接。
使用 stdio 时,由执行器启动服务器进程。请先在环境中安装服务器及其依赖项。
要运行 Python 版客户查询示例,请安装 MCP SDK。
python3 -m venv /workspace/mcp-demo
/workspace/mcp-demo/bin/python -m pip install 'mcp==1.26.0'
将 Python 服务器脚本保存为 /workspace/lookup_mcp.py。
如果使用 Ruby,请安装 mcp gem,并将 Ruby 服务器脚本保存为 /workspace/lookup_mcp.rb。
在 /workspace 中安装 @modelcontextprotocol/sdk 和 zod,然后将 TypeScript 服务器脚本保存为 /workspace/lookup_mcp.ts。在下方配置中,将 transport.command 设置为 Node 可执行文件的绝对路径,并将 transport.args 设置为 ["--experimental-strip-types", "/workspace/lookup_mcp.ts"]。此服务器使用 stdio,无需传入参数来指定传输方式。
Java 版本使用 io.modelcontextprotocol.sdk:mcp-core:1.1.5、io.modelcontextprotocol.sdk:mcp-json-jackson2:1.1.5 和 com.fasterxml.jackson.core:jackson-databind:2.18.11。它通过标准输入和标准输出提供同一个客户查询工具。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "customer-lookup", version: "1.0.0" });
server.registerTool(
"get_customer",
{
description: "Look up a customer in the example data.",
inputSchema: { customer_id: z.string() },
},
async ({ customer_id }) => {
const customers = new Map([
["123", { name: "Example Customer", plan: "pro" }],
]);
const result = { customer: customers.get(customer_id) ?? null };
return { content: [{ type: "text", text: JSON.stringify(result) }] };
}
);
await server.connect(new StdioServerTransport());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import sys
from mcp.server.fastmcp import FastMCP
server = FastMCP("customer-lookup", host="127.0.0.1", port=8765, stateless_http=True)
@server.tool()
def get_customer(customer_id: str) -> dict:
"""Look up a customer in the example data."""
customers = {"123": {"name": "Example Customer", "plan": "pro"}}
return {"customer": customers.get(customer_id)}
if __name__ == "__main__":
transport = sys.argv[1] if len(sys.argv) > 1 else "streamable-http"
server.run(transport=transport)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
type lookupInput struct {
CustomerID string `json:"customer_id" jsonschema:"Customer ID to look up"`
}
type customer struct {
Name string `json:"name"`
Plan string `json:"plan"`
}
type lookupOutput struct {
Customer *customer `json:"customer"`
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
server := mcp.NewServer(&mcp.Implementation{Name: "customer-lookup", Version: "1.0.0"}, nil)
mcp.AddTool(server, &mcp.Tool{Name: "get_customer", Description: "Look up a customer in the example data."},
func(_ context.Context, _ *mcp.CallToolRequest, input lookupInput) (*mcp.CallToolResult, lookupOutput, error) {
customers := map[string]*customer{"123": {Name: "Example Customer", Plan: "pro"}}
return nil, lookupOutput{Customer: customers[input.CustomerID]}, nil
})
// Default to stdio. Run `go run . http` to expose /mcp over HTTP.
if len(os.Args) < 2 || os.Args[1] != "http" {
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
return
}
port := "8765"
handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
mux := http.NewServeMux()
mux.Handle("/mcp", handler)
listener, err := net.Listen("tcp", "127.0.0.1:"+port)
if err != nil {
log.Fatal(err)
}
httpServer := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
fmt.Println("Listening on http://" + listener.Addr().String())
shutdownDone := make(chan struct{})
go func() {
defer close(shutdownDone)
<-ctx.Done()
shutdownCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
log.Print(err)
}
}()
if err := httpServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
<-shutdownDone
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53import com.fasterxml.jackson.databind.json.JsonMapper;
import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapper;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.transport.StdioServerTransportProvider;
import io.modelcontextprotocol.spec.McpSchema;
import java.io.FilterInputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
var mapper = new JacksonMcpJsonMapper(JsonMapper.builder().build());
var closed = new CountDownLatch(1);
var input =
new FilterInputStream(System.in) {
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
int count = super.read(bytes, offset, length);
if (count == -1) closed.countDown();
return count;
}
};
var transport = new StdioServerTransportProvider(mapper, input, System.out);
var tool =
McpSchema.Tool.builder()
.name("get_customer")
.description("Look up a customer in the example data.")
.inputSchema(
mapper,
"""
{"type":"object","properties":{"customer_id":{"type":"string"}},"required":["customer_id"],"additionalProperties":false}
""")
.build();
var server =
McpServer.sync(transport)
.serverInfo("customer-lookup", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())
.toolCall(
tool,
(exchange, request) -> {
String text =
"123".equals(request.arguments().get("customer_id"))
? "{\"customer\":{\"name\":\"Example Customer\",\"plan\":\"pro\"}}"
: "{\"customer\":null}";
return McpSchema.CallToolResult.builder()
.addTextContent(text)
.isError(false)
.build();
})
.build();
try {
closed.await();
} finally {
server.closeGracefully();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
HostApplicationBuilder builder = Host.CreateApplicationBuilder();
// Stdout is reserved for MCP messages, including during host startup.
builder.Logging.ClearProviders();
builder.Logging.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace);
builder.Services
.AddMcpServer(options =>
{
options.ServerInfo = new() { Name = "customer-lookup", Version = "1.0.0" };
})
.WithStdioServerTransport()
.WithTools<CustomerLookupTools>();
using IHost host = builder.Build();
await host.RunAsync();
[McpServerToolType]
public sealed class CustomerLookupTools
{
// Example data only; replace this collection with your customer data source.
private static readonly Dictionary<string, Customer> Customers =
new Dictionary<string, Customer>(StringComparer.Ordinal)
{
["123"] = new("Example Customer", "pro"),
};
// The parameter name is the public MCP schema key.
#pragma warning disable CA1707
[McpServerTool(Name = "get_customer")]
[Description("Look up a customer in the example data.")]
public static string GetCustomer(
[Description("The customer ID to look up.")] string customer_id
)
{
ArgumentNullException.ThrowIfNull(customer_id);
Customers.TryGetValue(customer_id, out Customer? customer);
return JsonSerializer.Serialize(new { customer });
}
#pragma warning restore CA1707
private sealed record Customer(
[property: System.Text.Json.Serialization.JsonPropertyName("name")] string Name,
[property: System.Text.Json.Serialization.JsonPropertyName("plan")] string Plan
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38require "mcp"
require "json"
class GetCustomer < MCP::Tool
tool_name "get_customer"
description "Look up a customer in the example data."
input_schema(type: "object", properties: { customer_id: { type: "string" } }, required: ["customer_id"])
def self.call(customer_id:, server_context:)
customers = {
"123" => {
name: "Example Customer",
plan: "pro"
}
}
result = { customer: customers[customer_id] }
MCP::Tool::Response.new(
[
{
type: "text",
text: JSON.generate(result)
}
], structured_content: result
)
end
end
server = MCP::Server.new(name: "customer-lookup", version: "1.0.0", tools: [GetCustomer])
# Use `ruby main.rb http` for the HTTP endpoint at /mcp; default to stdio.
if ARGV.first == "http"
require "rackup"
require "rackup/handler/webrick"
transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true, enable_json_response: true)
app = Rack::URLMap.new("/mcp" => transport)
Rackup::Handler::WEBrick.run(app, Host: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "8765")))
else
MCP::Server::Transports::StdioTransport.new(server).open
end
将服务器添加到 agent.tools。
如果使用 Ruby,请将 transport.command 设置为 Ruby 可执行文件的绝对路径,并将 transport.args 设置为 ["/workspace/lookup_mcp.rb", "stdio"]。请在该 Ruby 运行时中安装此 gem。stdio 参数指定脚本使用的传输方式。
1234567891011{
"type": "mcp",
"server_label": "customer_lookup",
"transport": {
"type": "stdio",
"command": "/workspace/mcp-demo/bin/python",
"args": ["/workspace/lookup_mcp.py", "stdio"],
"cwd": "/workspace"
},
"required": true
}
使用 stdio 时,必须指定 command,并将 cwd 设为绝对路径。args 为可选项。请省略 connection_origin。
发送一条消息,让智能体查询编号为 123 的客户。工具会返回客户名称 Example Customer 及其订阅的 pro 套餐。
对于 OpenAI 托管的 stdio MCP 服务器,请省略网络策略或将其设为 enabled。此类连接不支持 disabled 和 restricted 网络策略。
如果服务器允许匿名访问,请省略身份验证字段和 vault_ids。否则,请按以下方式为连接选择凭据来源。
- 单个会话的 HTTP 凭据。 创建会话时,设置
transport.authorization 或 transport.headers。Agents API 会加密这些值,并在返回的会话资源中省略它们。
- 可重复使用的 HTTP 凭据。 将 MCP 凭据存储在凭据库中,并通过
vault_ids 将凭据库关联到会话。只有从 OpenAI 发起的连接才能使用凭据库进行 MCP 身份验证。系统会根据服务器 URL 匹配凭据。如果有多个匹配项,请使用 credential_id 指定其中一个。
- stdio 凭据。 在环境中设置相应的环境变量,并在
transport.env_vars 中列出变量名。在该环境中运行的代码可以读取这些值。自托管会话不接受在 transport.env 中直接填写的值。
例如,HTTP 传输配置可以包含持有者令牌和另一个请求头。
123456{
"type": "http",
"server_url": "https://mcp.example.com/mcp",
"authorization": "Bearer YOUR_MCP_ACCESS_TOKEN",
"headers": { "X-Tenant-ID": "tenant_123" }
}
Authorization 只能使用一个来源。您可以在配置中直接指定,也可以使用凭据库中匹配的凭据。使用凭据库进行身份验证时,仍可设置其他请求头。从环境发起的 HTTP 连接不使用凭据库中的凭据。请直接配置身份验证信息或使用可信代理。
请勿在可重复使用的智能体定义、插件归档文件或日志中包含密钥等敏感信息。要防止智能体生成的代码访问凭据,请使用可信代理或服务器,由其在环境外部提供凭据。
设置 allowed_tools 可限制智能体能够发现和调用的工具。设置 required: true 后,如果服务器无法初始化,当前轮次就会失败。默认情况下,即使服务器无法初始化,当前轮次也可以继续。
有关全部 MCP 配置字段,请参阅创建会话 API 参考。
如果必需的服务器无法初始化,请查看 agent.session.turn.failed 中的错误信息。对于 stdio 服务器,还应检查 MCP 进程日志。
- 网络访问。 检查 URL 和
connection_origin。如果从环境发起连接,请确认执行器已连接,并且可以通过执行器所在的网络访问服务器。
- 凭据。 检查令牌或请求头。如果使用凭据库,请确认凭据与服务器 URL 匹配。
- 可执行文件和依赖项。 确认配置的命令可以在环境中运行。
- 工作目录。 在内联 stdio 配置中,将
cwd 设为现有目录的绝对路径。
- 插件可将 MCP 配置和技能打包,以便在多个会话中重复使用。
- 工具搜索介绍如何针对支持此功能的模型和提供商自动发现 MCP 工具。