Skip to content

Connectors

A Connector registers a tool server you operate, so Agents built on your Templates can call its tools. Unlike a plain MCP Server registration, every Connector tools/call carries a per-call Call Context: your server learns the actual Session owner’s platform User ID and maps it to your business accounts. Connectors belong to your Organization and are managed with an Organization API Key — keep it in your backend; User API Keys cannot manage or read Connectors. See authentication.

Two transports cover both reachability directions:

Transport Who dials whom Use when
streamable_http The platform calls your public HTTPS endpoint. Your server has a public address, or sits behind a public gateway (typical serverless).
tunnel Your server dials out to the platform over a persistent WebSocket. Your server has no public address: behind NAT, inside a corporate network, on a laptop.

Both transports speak MCP with the roles fixed: the platform is always the MCP client, your Connector is always the MCP server. Implement yours with the official MCP SDK — the worked examples show each transport end to end.

Register with an Organization API Key. A streamable_http Connector requires endpointUrl; a tunnel Connector takes none:

Terminal window
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"}'
  • The endpointUrl must be HTTPS without credentials or a fragment. The platform authenticates HTTP callbacks with a short-lived JWT, described below.
  • The 201 response returns an inactive Connector record, with no dedicated Connector Key or credential metadata.
  • displayName is unique within the Organization; a duplicate returns 409.

Activation discovers your tool catalog and freezes it for use:

Terminal window
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}'

Discovery lists your tools over the declared transport — for tunnel, over your first ready tunnel connection, so connect an instance before activating; with none ready, activation is refused with 409. A catalog holds at most 200 tools and each input schema at most 64 KiB. Schema pattern and patternProperties expressions are ECMAScript (u mode) regular expressions matched by a linear-time engine with RE2’s limits. A valid expression that engine cannot run refuses activation: lookaround, backreferences, modifier groups, Unicode property names RE2 does not know (such as \p{Script=Han}), repetition that expands beyond 1000, or patterns that compile too large. A pattern that is not valid ECMAScript does not refuse activation, but every call to that tool fails. Edits, Activation and deactivation require the current expectedConnectorVersion and increment it. After a 409, read the Connector again before retrying.

When the tools on an active streamable_http Connector change, post to /api/v1/org/connectors/<connectorId>/refresh-catalog with the same Organization API Key authentication and { "expectedConnectorVersion": <currentVersion> } body as Activation. The platform lists your tools under the same discovery limits and returns 200 with the refreshed observation. A failed discovery preserves the last successful catalog. A conflicting registration change or refresh returns 409. Catalog refresh keeps the Connector and endpoint versions, so subsequent Runs in existing Sessions discover their bindings from the updated catalog. Tunnel providers use tool-list change notifications.

While a Connector is active, edits (PATCH) are refused with 409, so live Agents never observe a half-mutated registration. Deactivate to reconfigure:

Terminal window
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}'

Deactivation takes the Connector’s tools offline: dispatches against runs frozen before re-activation fail with provider_unavailable, and new Turns freeze the current registration after you re-activate.

Attach the Connector to a Template in the Console Template editor: an Organization owner in Console opens the Template and adds it under MCP & Connectors, beside the Organization’s MCP Server registrations. The editor offers only available Connectors; an inactive one does not appear until activated. A saved reference that becomes unavailable stays visible, marked unavailable, until you remove it. The Template stores the reference exactly like an MCP Server registration, as tools.mcp[].serverId:

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

Through the Organization Template API, put the same reference in content.tools.mcp. Sessions created after the save can call the Connector’s tools, while existing Sessions keep the references they started with. Only active Connectors of the same Organization can be referenced; a Template save that names anything else fails with 409 agent_template_dependency_unavailable. The model calls each tool as mcp_<server>__<tool>, both parts derived from the discovered server and tool names (lowercased, non-alphanumerics collapsed to _) — the same naming partition as MCP Server tools.

Every Connector tools/call — on both transports — carries this block in 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
}
}
}
}
Field Meaning
callId The platform’s Operation id for this call — globally unique. Use it as your idempotency key: deduplicate effects by it.
sessionId The Session the calling Agent is serving. Map it to your own user or business records.
turnId The original Turn ID, present for tools that opt into same-Turn asynchronous execution.
organizationId The Organization that owns both the Session and the Connector.
userId The actual Session owner’s platform End User ID, including Scheduler-originated calls.
deadline ISO 8601 instant when the platform stops waiting. The current policy gives ordinary calls 300 seconds from dispatch and asynchronous-capable calls 60 seconds from publication. Abandon work after it passes.
attempt Always 1: the platform never retries a call automatically, so a side effect you applied is never re-executed.

The platform writes Call Context from persisted Session ownership. Interactive and Scheduler or other system-originated calls identify the same actual owner. The execution actor, Organization Key, external account ID and model arguments cannot replace or override userId. The same _meta key in a result is dropped.

Map the platform User to your business account

Section titled “Map the platform User to your business account”

Use (organizationId, userId) to look up your own business-account mapping, including optional external IDs you already keep. Existing Session mappings remain usable. You own business authorization, caching, forwarding and deduplication by callId. Model-controlled arguments and free text are never caller identity. The platform supplies neither a customer account-mapping service nor a separate signature for each Call Context.

To let a model continue while your tool runs, declare "_meta": { "tidb-link/execution": { "async": true } } on that tool in tools/list. The tool’s input schema must leave the top-level argument async available to the platform. The platform exposes that optional boolean to the model and strips it before validating and forwarding your arguments.

Whether the model waits or continues, keep the ordinary HTTP or tunnel tools/call open until the final MCP result. The Call Context deadline is 60 seconds from publication in both modes. Reuse its callId and original deadline for any redelivery inside your service. The platform acknowledgement confirms publication. The Turn stays open until the model receives the outcome, and stopping the Turn closes the wait. An action your service has already initiated may still take effect.

An opted-in tool can include effect information in a final error. Use isError: true and "_meta": { "tidb-link/outcome": { "effect": "unknown", "code": "device_timeout" } }. Choose did_not_happen only when your service can verify that the effect did not occur. Use a stable code of 1 to 64 characters, starting with a lowercase ASCII letter and followed by lowercase letters, digits or underscores. An omitted or malformed outcome or a rejected result leaves the effect unknown. A valid reported unknown returns result_unknown with confirmed delivery of the error, while losing the response after dispatch leaves delivery indeterminate.

Before each call on either transport, the platform lists the live tools and checks the selected tool against the declaration the AgentRun froze. Its server name, tool name, title, description, input and output schemas, and asynchronous execution opt-in must remain the same. Adding, removing, or changing other tools in a valid catalog leaves the selected tool callable. A missing or changed selected tool returns provider_unavailable before tools/call.

Return ordinary MCP results. Keep content to text blocks and resource_link references: image, audio and embedded-resource payloads are rejected by the platform’s result projection, as are results over the limits (1 MiB of text, 10,000 content entries, 32 levels of structure). A rejected result reaches the model as a result_* or unsupported_binary_result tool error, so fix the tool rather than the Agent.

Report a business failure — unknown order, declined payment — as a normal result with isError: true and explanatory text:

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

The model receives your text as the tool error (remote_tool_error) and can explain the failure or retry with corrected arguments.

Failures before or around dispatch reach the model as structured tool errors:

Code Meaning Did your server see the call?
invalid_arguments The model’s arguments failed the frozen schema. No — never dispatched.
forbidden The Session’s Organization did not match the Connector’s; the platform also raises a security alert. No.
provider_unavailable Your endpoint was unreachable, no ready tunnel instance existed, the live catalog could not verify the frozen tool declaration, or the per-Connector concurrency bound was full. Nothing is queued. No.
timeout The call’s deadline passed before a result arrived. Possibly — indeterminate once dispatch started.
result_unknown Dispatch started and the result was lost in transit, or an opted-in tool reported an unknown effect. Indeterminate on response loss, confirmed on a provider error.
remote_tool_error Your tool returned isError: true; the model sees your error text. Yes.

The platform never retries automatically. After timeout or result_unknown, reconcile by callId before assuming the effect did not happen — and make side-effecting tools idempotent around it.

The platform sends Authorization: Bearer <JWT> for initialization, Tool Catalog Discovery and tool calls. Obtain public verification keys from GET /api/v1/connectors/jwks at your trusted platform URL; the route needs no Organization Key. Cache these public keys locally and select the key by the token’s kid. Never obtain keys from an untrusted token-supplied URL.

Verify the Ed25519 signature (alg: EdDSA), iss: tidb-link/connector-callback/v1, aud: tidb-link/connector, and the exact organizationId and connectorId for your service. Require integer iat and exp, an unexpired token and a positive lifetime of at most 60 seconds. The token grants callback transport authentication only; it grants no Organization API, tunnel or business-account authority. The worked example below verifies these fields using cached JWKS and Node’s crypto library.

A valid JWT may be used repeatedly, including for different Users within that Organization and Connector. Platform callbacks may use the same token or different valid tokens. There is no token-acquisition API, single-use requirement or per-request content signature. You choose internal forwarding, caching, authorization and call deduplication within the token’s scope and expiry.

Initialization and catalog discovery have no Call Context, User or Session. An ordinary tool call adds its independently derived Session-owner context. The JWT does not sign that request’s arguments or Call Context.

Deactivation immediately stops new platform dispatches. A captured JWT can still pass offline verification until expiry. JWT expiry controls admission to your service; an admitted call keeps its original Call Context deadline, which may be later than the token expiry.

Open the tunnel as a WebSocket client:

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>

The Organization Key supplies Organization authority. X-Ti-Connector-Id must select an existing tunnel Connector in that Organization. User Keys, browser identities and foreign-Organization targets are refused. Inactive Connectors accept connections so Activation can discover their catalog.

The instance id is your own non-empty string of at most 128 bytes without control characters, naming this instance of your server. On the socket the platform is the MCP client: it drives initialize, then tools/list and tools/call, and your SDK server answers. Each text frame carries exactly one raw JSON-RPC 2.0 message — no envelope, no batching; binary frames are a protocol error.

Your side of the socket may send notifications only:

  • notifications/tools/list_changed asks the platform to rediscover your catalog: the platform re-lists your tools over a ready connection and persists the refreshed catalog for new Turns while the Connector is active.
  • notifications/progress is accepted but never extends the announced call deadline.

Requests initiated by your side close the socket. The close codes:

Code Meaning
1000 Normal closure.
1001 Heartbeat timeout — two consecutive platform pings went unanswered.
4001 Authentication failed: the key is missing, malformed, unknown, revoked or stale.
4003 The authenticated Connector is not a tunnel Connector.
4008 A reconnecting instance with the same X-Ti-Connector-Instance took over.
4009 Protocol error: invalid frames, or a request from your side.

The platform pings every 20 seconds and disconnects after two missed pongs; the ws library answers pings automatically, so a healthy process needs no heartbeat code. Reconnect with backoff after any close. A 4008 means another process connected with your instance id — usually a deliberate second deployment; back off rather than fighting it in a tight loop. Refusals before the upgrade are plain HTTP: 400 for a malformed upgrade, 426 for a non-WebSocket request, 429 while the replica is at its admission limit, 503 while the gateway is stopping.

Run as many instances as you need: calls ride any ready connection, and a reconnecting instance atomically replaces its own stale connection, so deploys and crashes converge in seconds. With no ready instance, calls fail immediately with provider_unavailable — nothing is queued platform-side.

Rotating or revoking the exact Organization credential used by a connection durably prevents new dispatch and actively closes its old sockets on every serving replica, including when rotation retains the Key ID. Other valid Keys’ connections remain usable. Physical close notifications may arrive later; an open socket never establishes continuing authority. Key changes neither deactivate the Connector nor rewrite a Run’s selected capabilities.

An already-dispatched call whose response is lost may finish as result_unknown, without automatic retry or cancellation of the entire accepted Turn. Closing a socket does not undo an external effect. Ready instances are available only on the replica accepting their sockets; there is no cross-replica tool-call routing.

Both examples use the official MCP TypeScript SDK v2 (@modelcontextprotocol/server) and implement one tool, list_orders, that authorizes from the Call Context. In the SDK, the tool handler’s context carries the request’s _meta at ctx.mcpReq._meta.

A stateless server on node:http via the SDK’s Node adapter (@modelcontextprotocol/node), verifying the platform JWT locally before handing the request to 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);

The same MCP server, attached to a custom Transport over one WebSocket the server dials out. The platform pings; ws pongs for you:

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();

When your tools change, call server.sendToolListChanged() and the platform rediscovers the catalog over a ready connection.

This contract uses the platform’s protocol namespace throughout, exactly as implemented: the Call Context key is tidb-link/context, the tunnel subprotocol is tidb-link.connector.v1, and the instance header is X-Ti-Connector-Instance. Use all three verbatim.

Full request and response schemas for the management routes live in the API reference; the tunnel endpoint is documented there as GET /api/v1/connectors/ws.