跳转到内容

Connector

Connector 用于注册一台由你运营的工具服务器,让基于你的 Template 构建的 Agent 可以调用它的工具。与普通的 MCP Server 注册不同,每次 Connector tools/call 都携带逐次调用的 Call Context:你的服务器由此得知实际 Session 所有者的平台 User ID,并将其映射到自己的业务账号。Connector 属于你的 Organization,使用 Organization API Key 管理——请把它保存在你的后端;User API Key 无法管理或读取 Connector。参见认证。

两种传输方向覆盖两种可达性:

传输 谁发起连接 适用场景
streamable_http 平台调用你的公网 HTTPS 端点。 你的服务器有公网地址,或位于公网网关之后(典型的 Serverless 场景)。
tunnel 你的服务器通过持久 WebSocket 向平台发起外连。 你的服务器没有公网地址:位于 NAT 之后、企业内网,或开发机器上。

两种传输都使用 MCP,且角色固定:平台始终是 MCP 客户端,你的 Connector 始终是 MCP 服务端。请用官方 MCP SDK 实现——下面的完整示例分别演示了两种传输。

使用 Organization API Key 注册。streamable_http Connector 必须提供 endpointUrl;tunnel Connector 不提供:

终端窗口
curl -X POST https://<your-agent-service-host>/api/v1/org/connectors \
-H "Authorization: Bearer $ORGANIZATION_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"displayName":"Orders","transport":"streamable_http","endpointUrl":"https://tools.example.com/mcp"}'
  • endpointUrl 必须是 HTTPS,且不含凭据或 fragment。平台用短期 JWT 认证 HTTP 回调,详见下方说明。
  • 201 响应返回 inactive Connector 记录,不签发专用 Connector Key,也不返回凭据元数据。
  • displayName 在 Organization 内唯一;重名返回 409。

激活会发现你的工具目录并将其冻结待用:

终端窗口
curl -X POST https://<your-agent-service-host>/api/v1/org/connectors/<connectorId>/activate \
-H "Authorization: Bearer $ORGANIZATION_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"expectedConnectorVersion":1}'

发现通过声明的传输列出你的工具——对 tunnel 而言,通过你的第一条就绪隧道连接进行,因此请先连接一个实例再激活;没有就绪实例时激活会被拒绝并返回 409。一个目录最多容纳 200 个工具,每个输入 schema 最大 64 KiB。schema 中的 pattern 和 patternProperties 是 ECMAScript(u 模式)正则,由遵循 RE2 限制的线性时间引擎匹配。该引擎无法运行的合法正则会导致激活被拒绝:前瞻和后顾、反向引用、修饰符分组、RE2 不认识的 Unicode 属性名(例如 \p{Script=Han})、展开后超过 1000 次的重复,或编译后过大的正则。不是合法 ECMAScript 的正则不会导致激活被拒绝,但对该工具的每次调用都会失败。编辑、激活和停用都要求传入当前 expectedConnectorVersion,成功后版本递增。收到 409 后,先重新读取 Connector 再重试。

已激活的 streamable_http Connector 工具发生变化时,向 /api/v1/org/connectors/<connectorId>/refresh-catalog 发送 POST。认证与激活相同,使用 Organization API Key,并在请求体 { "expectedConnectorVersion": <currentVersion> } 中传入当前版本。平台按激活时的发现限制重新列出工具,成功后返回 200 和更新后的观测信息。发现失败时保留上次成功的目录,注册变更或并发刷新发生冲突时返回 409。刷新保留 Connector 与端点的版本,已有 Session 的后续 Run 从新目录获取工具绑定。隧道服务端使用工具列表变更通知。

当 Connector 处于 active 状态时,编辑(PATCH)被拒绝并返回 409,因此在线 Agent 绝不会观察到改了一半的注册。先停用以重新配置:

终端窗口
curl -X POST https://<your-agent-service-host>/api/v1/org/connectors/<connectorId>/deactivate \
-H "Authorization: Bearer $ORGANIZATION_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"expectedConnectorVersion":2}'

停用会让该 Connector 的工具下线:基于重新激活前冻结的 Run 发起的调用会以 provider_unavailable 失败,重新激活后新的 Turn 会冻结当前注册状态。

在 Console 的 Template 编辑器中把 Connector 关联到 Template:Organization 的 owner 在 Console 中打开 Template,在 MCP 与 Connector 下添加它,它与 Organization 的 MCP Server 注册列在一起。编辑器只提供可用的 Connector;未激活的 Connector 在激活前不会出现。已保存的引用如果变为不可用,会继续显示并标为不可用,直到你移除它。Template 以与 MCP Server 注册完全相同的方式保存该引用,即 tools.mcp[].serverId:

{ "tools": { "mcp": [{ "serverId": "conn_…" }] } }

通过组织模板 API 时,把同样的引用放进 content.tools.mcp。保存之后创建的 Session 可以调用该 Connector 的工具,已有 Session 保留其创建时的引用。只能引用同一 Organization 内处于 active 状态的 Connector;引用其他对象的 Template 保存会失败并返回 409 agent_template_dependency_unavailable。模型以 mcp_<server>__<tool> 调用每个工具,两部分分别由发现到的服务器名和工具名派生(转小写、非字母数字折叠为 _)——与 MCP Server 工具使用同一个命名分区。

每次 Connector tools/call——两种传输皆然——都在 params._meta 中携带如下块:

{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "list_orders",
"arguments": { "status": "open" },
"_meta": {
"tidb-link/context": {
"callId": "op_01JAB…",
"sessionId": "sess_…",
"organizationId": "org_…",
"userId": "usr_…",
"deadline": "2026-10-17T08:30:05.123Z",
"attempt": 1
}
}
}
}
字段 含义
callId 平台为这次调用生成的 Operation id——全局唯一。把它用作你的幂等键:按它去重副作用。
sessionId 发起调用的 Agent 正在服务的 Session。把它映射到你自己的用户或业务记录。
turnId 原始 Turn 的 ID。仅在工具启用同一 Turn 内的异步执行时提供。
organizationId 同时拥有该 Session 与该 Connector 的 Organization。
userId 实际 Session 所有者的平台 End User ID,包括 Scheduler 发起的调用。
deadline 平台停止等待结果的 ISO 8601 时刻。当前策略下,普通调用从派发起有 300 秒,支持异步执行的调用从发布起有 60 秒。超过截止时间后请放弃工作。
attempt 恒为 1:平台不会自动重试调用,因此你已执行的副作用不会被平台重复执行。

Call Context 由平台从持久化的 Session 所有权写入,交互式与 Scheduler 等系统发起的调用使用同一个真实所有者。执行 actor、Organization Key、外部账号 ID 和模型参数都不能替代或覆盖 userId。结果中相同的 _meta 键会被丢弃。

使用 (organizationId, userId) 查询你自己的业务账号映射,包括你已经保存的可选外部 ID;已有的 Session 映射也可以继续使用。业务授权、缓存、内部转发与按 callId 去重仍由你负责。不要把模型可影响的参数或文本当作调用者身份。平台不提供客户账号映射服务,也不对每次 Call Context 做独立签名。

要让模型在工具运行期间继续执行,请在 tools/list 返回的工具声明中加入 "_meta": { "tidb-link/execution": { "async": true } }。工具的输入 schema 必须将顶层 async 参数留给平台。平台向模型提供这个可选的布尔参数,并在校验和转发工具参数之前移除它。

无论模型选择等待还是继续执行,请保持 HTTP 或隧道上的 tools/call 请求,直到返回最终 MCP 结果。两种模式下的 Call Context 截止时间都是发布后 60 秒。服务内部重新投递时,沿用原 callId 和截止时间。平台回执仅确认调用已发布。Turn 会保持运行,直到模型收到结果。停止 Turn 会结束等待,服务已经发起的动作仍可能生效。

声明支持异步执行的工具可以在最终错误结果中报告动作效果。设置 isError: true,并加入 "_meta": { "tidb-link/outcome": { "effect": "unknown", "code": "device_timeout" } }。只有当服务能够确认动作未生效时,才使用 did_not_happen。错误码应保持稳定,长度为 1 至 64 个字符,以 ASCII 小写字母开头,其余字符只能是小写字母、数字或下划线。缺少效果信息、格式无效或结果被平台拒绝时,动作效果均为未知。有效的 unknown 会返回 result_unknown,并确认平台收到了工具错误。派发后响应丢失时,平台无法确认调用是否送达。

每次调用前,平台都会通过对应传输列出当前可用的工具,并将选中工具与 AgentRun 冻结的声明核对。服务端名称、工具名称、标题、描述、输入和输出 schema,以及是否声明支持异步执行,都必须一致。有效目录中其他工具的增删改不影响选中工具的调用。如果选中工具缺失或声明发生变化,平台会在发出 tools/call 前返回 provider_unavailable。

返回普通的 MCP 结果。内容只使用 text 块和 resource_link 引用:image、audio 和 embedded resource 负载会被平台的结果投影拒绝,超出限额(1 MiB 文本、10,000 个内容条目、32 层结构)的结果同样如此。被拒绝的结果会以 result_* 或 unsupported_binary_result 工具错误到达模型,因此应当修正工具,而不是修正 Agent。

业务失败——订单不存在、支付被拒——以带 isError: true 和说明文字的正常结果报告:

{
"content": [
{ "type": "text", "text": "Order 4711 has already shipped and cannot be cancelled." }
],
"isError": true
}

模型会把你的文本作为工具错误(remote_tool_error)收到,并可以解释失败原因或用修正后的参数重试。

派发前或派发过程中的失败以结构化工具错误到达模型:

错误码 含义 你的服务器是否收到了这次调用?
invalid_arguments 模型参数未通过冻结 schema 校验。 否——从未派发。
forbidden Session 的 Organization 与该 Connector 的不一致;平台同时会发出安全告警。 否。
provider_unavailable 你的端点不可达、没有就绪的隧道实例、在线目录无法验证选中工具的冻结声明,或该 Connector 的并发上限已满。平台会立即返回错误。 否。
timeout 结果未能在调用的 deadline 之前到达。 可能——派发一旦开始,效果即不确定。
result_unknown 派发后结果在传输中丢失,或声明支持异步执行的工具报告动作效果未知。 响应丢失时无法确认。收到工具错误时已确认送达。
remote_tool_error 你的工具返回了 isError: true;模型会看到你的错误文本。 是。

平台绝不自动重试。遇到 timeout 或 result_unknown 后,先按 callId 对账,再假定副作用未发生——并让有副作用的工具围绕它做到幂等。

平台在初始化、工具目录发现和工具调用中发送 Authorization: Bearer <JWT>。从你信任的平台地址读取 GET /api/v1/connectors/jwks 公钥集;此路由不需要 Organization Key。将公钥缓存在本地,按 token 的 kid 选择验证密钥。不要从不可信 token 给出的 URL 获取密钥。

验证 Ed25519 签名(alg: EdDSA)、iss: tidb-link/connector-callback/v1、aud: tidb-link/connector,以及服务预期的准确 organizationId 和 connectorId。要求 iat、exp 为整数、token 尚未过期,且有效期为正数并且不超过 60 秒。token 只提供回调传输认证,不授予 Organization API、隧道或业务账号权限。下方示例使用缓存的 JWKS 和 Node crypto 验证这些字段。

有效 JWT 可以重复使用,也可以用于同一 Organization、Connector 内不同 User 的调用。平台可以复用 token,也可以发送另一个有效 token。没有 token 获取 API、单次消费要求或逐请求内容签名。你可以在 token 的作用域和有效期内自行选择内部转发、缓存、授权与调用去重策略。

初始化和目录发现没有 Call Context、User 或 Session。普通工具调用另行携带由平台从 Session 所有权推导的上下文;JWT 不对该请求的参数或 Call Context 做签名声明。

停用会立即阻止新的平台派发。已经签发的 JWT 在过期前仍可通过离线验证。JWT 过期时间只约束服务接收请求的准入;已经接收的调用保留原有 Call Context 截止时间,该时间可以晚于 token 过期时间。

以 WebSocket 客户端身份打开隧道:

wss://<your-agent-service-host>/api/v1/connectors/ws
Sec-WebSocket-Protocol: tidb-link.connector.v1
Authorization: Bearer <organizationApiKey>
X-Ti-Connector-Id: <connectorId>
X-Ti-Connector-Instance: <your-instance-id>

Organization Key 决定 Organization 权限;X-Ti-Connector-Id 必须选择该 Organization 已存在的 tunnel Connector。User Key、浏览器身份以及其他 Organization 的 Connector 都无法接入。inactive Connector 也接受连接,以便激活时进行发现。

实例 id 是你自定义的非空字符串(至多 128 字节、不含控制字符),用于命名你的服务器的这个实例。在这条 socket 上,平台是 MCP 客户端:它驱动 initialize,随后是 tools/list 和 tools/call,由你的 SDK 服务端应答。每个文本帧恰好携带一条原始 JSON-RPC 2.0 消息——没有信封、没有打包;二进制帧属于协议错误。

你这侧的 socket 只能发送通知:

  • notifications/tools/list_changed 请求平台重新发现你的目录:平台会通过一条就绪连接重新列出你的工具,并在 Connector 处于 active 期间持久化刷新后的目录,供新的 Turn 使用。
  • notifications/progress 会被接受,但绝不会延长已宣告的调用截止时间。

由你这侧发起的请求会导致 socket 被关闭。关闭码如下:

关闭码 含义
1000 正常关闭。
1001 心跳超时——连续两次平台 ping 未得到应答。
4001 认证失败:密钥缺失、格式错误、未知、已吊销或已过期。
4003 已认证的 Connector 不是 tunnel Connector。
4008 一个使用相同 X-Ti-Connector-Instance 重连的实例接管了连接。
4009 协议错误:非法帧,或来自你这侧的请求。

平台每 20 秒 ping 一次,连续两次未收到 pong 即断开;ws 库会自动应答 ping,因此健康的进程无需编写心跳代码。任何关闭之后都带退避重连。4008 表示另一个进程用你的实例 id 接入了——通常是有意的第二部署;请退避而不是用紧凑循环与之争抢。升级之前的拒绝是普通 HTTP:升级请求非法为 400,非 WebSocket 请求为 426,副本达到准入上限时为 429,网关停止中为 503。

实例可以按需运行任意多个:调用会落在任意一条就绪连接上;使用相同 id 重连的实例会原子地替换自己的陈旧连接,因此部署与崩溃都能在数秒内收敛。当没有就绪实例时,调用立即以 provider_unavailable 失败——平台侧不做任何排队。

轮换或吊销连接使用的准确 Organization 凭证,会在持久化变更后阻止新派发,并使各副本主动关闭其旧连接;同一 Key ID 的旧 secret 也会失效。其他有效 Key 的连接保留。socket 关闭通知可能稍后到达,开放的 socket 不代表持续权限。Key 变更不会停用 Connector 或重写 Run 的能力选择。

已经发送的调用如果因断连无法验证结果,会返回 result_unknown,不会自动重试,也不会仅因此取消整个已接受的 Turn。关闭连接不代表撤销外部副作用。实例连接只在接收它的副本上可用;平台没有跨副本工具路由。

两个示例都使用官方 MCP TypeScript SDK v2(@modelcontextprotocol/server),实现同一个工具 list_orders,并基于 Call Context 做授权。在该 SDK 中,工具处理器的上下文在 ctx.mcpReq._meta 处携带请求的 _meta。

基于 node:http 的无状态服务器,使用 SDK 的 Node 适配器(@modelcontextprotocol/node),先用本地公钥校验平台 JWT,再交给 MCP:

import { createServer } from 'node:http';
import { createPublicKey, verify, type JsonWebKey } from 'node:crypto';
import { McpServer } from '@modelcontextprotocol/server';
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
import { z } from 'zod';
const PLATFORM_URL = process.env.PLATFORM_URL!;
const ORGANIZATION_ID = process.env.ORGANIZATION_ID!;
const CONNECTOR_ID = process.env.CONNECTOR_ID!;
// Fetch only from your trusted platform URL; cache public keys locally.
const jwks: { keys: Array<JsonWebKey & { kid: string }> } = await fetch(
new URL('/api/v1/connectors/jwks', PLATFORM_URL),
).then((response) => {
if (!response.ok) throw new Error('JWKS unavailable');
return response.json();
});
const keys = new Map(jwks.keys.map((key) => [key.kid, key]));
function authenticate(authorization: string | undefined): void {
const bearer = /^Bearer ([^\s,]+)$/i.exec(authorization ?? '');
const parts = bearer?.[1].split('.');
if (!parts || parts.length !== 3) throw new Error('Invalid credential');
const [headerPart, payloadPart, signaturePart] = parts;
const header = JSON.parse(Buffer.from(headerPart, 'base64url').toString());
const claims = JSON.parse(Buffer.from(payloadPart, 'base64url').toString());
const key = keys.get(header.kid);
const now = Math.floor(Date.now() / 1000);
if (
header.alg !== 'EdDSA' ||
!key ||
key.kty !== 'OKP' ||
key.crv !== 'Ed25519' ||
!verify(
null,
Buffer.from(`${headerPart}.${payloadPart}`),
createPublicKey({ key, format: 'jwk' }),
Buffer.from(signaturePart, 'base64url'),
) ||
claims.iss !== 'tidb-link/connector-callback/v1' ||
claims.aud !== 'tidb-link/connector' ||
claims.organizationId !== ORGANIZATION_ID ||
claims.connectorId !== CONNECTOR_ID ||
!Number.isInteger(claims.iat) ||
!Number.isInteger(claims.exp) ||
claims.iat > now ||
claims.exp <= now ||
claims.exp <= claims.iat ||
claims.exp - claims.iat > 60
)
throw new Error('Invalid credential');
}
const CALL_CONTEXT_KEY = 'tidb-link/context';
const callContextSchema = z.object({
callId: z.string().min(1),
sessionId: z.string().min(1),
organizationId: z.literal(ORGANIZATION_ID),
userId: z.string().min(1),
deadline: z.string().datetime(),
attempt: z.literal(1),
});
const callContext = (meta: unknown) =>
callContextSchema.parse((meta as Record<string, unknown> | undefined)?.[CALL_CONTEXT_KEY]);
const buildServer = (): McpServer => {
const server = new McpServer({ name: 'orders', version: '1.0.0' });
server.registerTool(
'list_orders',
{
description: 'List recent orders for the calling user.',
inputSchema: z.object({ status: z.string().optional() }),
},
async (args, ctx) => {
const { organizationId, userId, callId, deadline } = callContext(ctx.mcpReq._meta);
// Business-account mapping and authorization belong to your service.
const account = await yourAccounts.lookupByPlatformUser(organizationId, userId);
if (!account) {
return { content: [{ type: 'text', text: 'Unknown user.' }], isError: true };
}
const orders = await yourOrders.listRecent(account, {
status: args.status,
idempotencyKey: callId,
notAfter: new Date(deadline),
});
return { content: [{ type: 'text', text: JSON.stringify(orders) }] };
},
);
return server;
};
createServer(async (req, res) => {
try {
authenticate(req.headers.authorization);
} catch {
res.writeHead(401).end();
return;
}
// Stateless: one server and transport per request, no session tracking.
const server = buildServer();
const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on('close', () => {
void transport.close();
void server.close();
});
await server.connect(transport);
await transport.handleRequest(req, res);
}).listen(8080);

同一个 MCP 服务器,通过一条由服务器主动外连的 WebSocket 挂到自定义 Transport 上。平台负责 ping;ws 会替你 pong:

import { McpServer, type JSONRPCMessage, type Transport } from '@modelcontextprotocol/server';
import WebSocket from 'ws';
class TunnelTransport implements Transport {
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
constructor(private readonly socket: WebSocket) {}
start(): Promise<void> {
this.socket.on('message', (data, binary) => {
if (binary) return; // binary frames are a protocol error platform-side; never send them
this.onmessage?.(JSON.parse(data.toString('utf8')));
});
this.socket.on('close', () => this.onclose?.());
this.socket.on('error', (error) => this.onerror?.(error));
return Promise.resolve();
}
send(message: JSONRPCMessage): Promise<void> {
return new Promise((resolve, reject) =>
this.socket.send(JSON.stringify(message), (error) => (error ? reject(error) : resolve())),
);
}
async close(): Promise<void> {
this.socket.close();
}
}
const connect = (): void => {
const ws = new WebSocket(
'wss://<your-agent-service-host>/api/v1/connectors/ws',
'tidb-link.connector.v1', // the subprotocol is required
{
headers: {
authorization: `Bearer ${process.env.ORGANIZATION_API_KEY}`,
'x-ti-connector-id': process.env.CONNECTOR_ID!,
'x-ti-connector-instance': process.env.INSTANCE_ID ?? 'instance-1',
},
},
);
ws.on('open', async () => {
const server = buildServer(); // the same McpServer as above
await server.connect(new TunnelTransport(ws));
});
ws.on('close', (code) => {
// 4001: check the key. 4008: another same-named instance took over — back off.
setTimeout(connect, 1000 + Math.random() * 4000);
});
};
connect();

工具变化时调用 server.sendToolListChanged(),平台会通过一条就绪连接重新发现目录。

本契约统一使用平台的协议命名空间,均为实现的现状:Call Context 的键是 tidb-link/context,隧道子协议是 tidb-link.connector.v1,实例请求头是 X-Ti-Connector-Instance。三者都请按原文使用。

管理路由的完整请求与响应 schema 见 API 参考;隧道端点在其中记录为 GET /api/v1/connectors/ws。