Skip to main content

MCP registry and tool catalog

packages/agent-mcp defines the MCP server registry (one YAML file per upstream server), the compile step that turns a job's grants into a tool catalog, and the helpers the gateway uses to pin and sanitize untrusted tool schemas. The gateway serves the catalog on POST /mcp of the data listener (apps/gateway/src/mcp/route.ts) and calls upstream servers through a pinned client (apps/gateway/src/mcp/upstream.ts).

Production state. The baked org policy sets tools.allow: [], and the image's /registry directory is empty (GATEWAY_REGISTRY_DIR=/registry; an empty directory is a valid empty registry). So no tool reaches any catalog and tools/list returns an empty list. Registry entries in the repository are test fixtures only; real app-MCP entries are user-owned (plan U2). The identity exchange is tested against a fake IdP only.

Registry file format​

loadRegistry(dir, { allowLoopbackHttp }) reads every *.yaml or *.yml file directly in the directory (non-recursive, sorted), one server per file, at most MAX_REGISTRY_FILE_BYTES = 262 144 bytes each. YAML rules match the policy loader: core schema, no merge keys, unique keys, maxAliasCount: 0. A duplicate server id refuses startup.

MCPServerConfig (strict):

FieldType and rule
id^[a-z][a-z0-9-]{0,63}$
transportonly http ("unsupported in P2.G" otherwise)
endpointURL; see endpoint rules below
enabledboolean; disabled servers provide no tools
allowedAgentsrole policy ids allowed to use this server (exact names)
permissions.tools[]RegistryTool entries
identitymode (obo or service), audience (exact), scopes (exact names)

RegistryTool (strict):

FieldRule
namegateway tool name, ToolName regex (knowledge.search style, no wildcards)
upstreamName^[A-Za-z0-9_.-]{1,128}$, the tool's name on the upstream server
description1 to 2048 chars; shown to the model wrapped as untrusted; the upstream's own description is never forwarded
scopesexact names; must be covered by the server identity's scopes
schemaSha25664 hex chars; sha256 of the upstream tool's canonical inputSchema (the rug-pull pin)

Endpoint rules (endpointProblem):

  • no username or password, no fragment;
  • an IP literal host (any IPv4 form normalized by WHATWG URL, or a bracketed IPv6) is refused; registry endpoints are DNS names;
  • https: only; plain http: only for 127.0.0.1 under the test flag (GATEWAY_TEST_UPSTREAM=1 with NODE_ENV=test).

Catalog compile (GV7)​

compileCatalog(grants, registry, role) builds ToolCatalog, a record keyed by gateway tool name whose entries carry serverId, upstreamName, endpoint, description, identity, scopes, schemaSha256. Every granted tool must pass all checks or the whole compile throws (no partial catalog):

The catalog is compiled once at registration and stays a snapshot for the job's lifetime: a server disabled mid-job stays in that job's catalog until the TTL; revoke is the kill path (plan section 12). The exposed name in tools/list is the gateway name with . replaced by _ (exposedName); the CLI shows it as mcp__agentforge__<name>.

RegistryErrorCode values: read_failed, too_large, parse_failed, invalid_server, duplicate_server, endpoint_not_allowed (loader), and tool_not_provided, agent_not_allowed, scope_not_granted, duplicate_tool, egress_not_allowed (compile). Loader errors refuse startup; compile errors at registration are a 400.

The /mcp route​

Stateless Streamable HTTP: a new MCP Server and WebStandardStreamableHTTPServerTransport per request, no session id issued or honoured (sessionIdGenerator: undefined, JSON responses). POST only; no GET stream, no DELETE.

Checks and audit reasons​

CheckResponseAudit reason (kind = tool)
kill switch on or unreadable503 api_errordisabled
ledger read throws401ledger_error
row missing or settled (registration revoked)401 registration_staleregistration_stale
body over 1 MiB (MCP_BODY_MAX_BYTES)413body_too_large
body not received in time408client_aborted
JSON-RPC batch (first non-whitespace byte is [)400invalid_json
arguments nested deeper than MAX_JSON_DEPTH (64)JSON-RPC errorargs_invalid
tool not in the catalogJSON-RPC error, no upstream request of any kindtool_not_granted
tool in requireApprovalJSON-RPC errortool_not_granted
arguments over MCP_ARGS_MAX_BYTES (256 KiB)JSON-RPC errorargs_too_large
identity mode mismatch, no subject bound, exchange failedJSON-RPC errorexchange_denied
upstream schema missing, changed, or uses a refused keywordJSON-RPC errorschema_changed
ajv refuses the schema or the arguments do not validateJSON-RPC errorargs_invalid
upstream response over MCP_RESULT_MAX_BYTES (1 MiB)JSON-RPC errorresult_too_large
upstream sent a server-to-client requestJSON-RPC errorserver_request_denied
upstream timeout (GATEWAY_MCP_TIMEOUT_MS) or errorJSON-RPC error, decision allowupstream_timeout, upstream_error
success with non-text blocks or structuredContentresult (text only)content_stripped (decision allow)
resources/*, prompts/*, any other methodMethodNotFoundmethod_not_found

Tool-call audit rows carry args_sha256 (sha256 of the JSON arguments) and never the arguments. Anything unexpected becomes an audited refusal, never an unaudited 500 (L3).

Schema pin and sanitizing​

HelperBehaviour
schemaSha256(schema)sha256 hex of JSON.stringify of the schema with keys sorted at every level; throws past depth 64
usesPattern(schema)true if pattern, patternProperties or uniqueItems appears anywhere, or nesting exceeds 64 (ReDoS and O(n²) protection); such a schema is never forwarded or compiled
stripAnnotations(schema)removes title, description, examples, default, $comment at every schema position, keeps property names and literal keywords (enum, const, required, dependentRequired); the model sees this copy, the pin and validation use the original
tooDeep(v, 64)bounded depth check before anything recurses over untrusted JSON

Argument validation uses a fresh Ajv({ allowUnionTypes: false, strict: true, validateFormats: false }) per pinned sha256, cached by that sha256 (L7); a schema ajv refuses is cached as refused.

Result wrapping (GV4)​

Only text content blocks survive. They are joined and wrapped as

<untrusted-tool-result-<16 hex nonce> source="<serverId>">…</untrusted-tool-result-<nonce>>

The nonce is 8 random bytes per call, so the upstream cannot forge the closing tag; any </untrusted-tool-result sequence inside is escaped as &lt;/untrusted-tool-result. The result carries _meta entries agentforge/provenance: untrusted and agentforge/source: <serverId>. Descriptions in tools/list are wrapped the same way with untrusted-tool-description (no nonce). Tagging is advisory to the model; least privilege is the control (plan residual risk).

Upstream client​

withUpstream opens one MCP client session per operation:

  • Client declares no capabilities (no sampling, elicitation or roots). Its fallbackRequestHandler rejects any server-to-client request and marks the session failed even if the upstream then answers normally.
  • pinnedFetch only reaches the endpoint's origin (scheme, host, port), sets redirect: 'error', and errors the body stream past 1 MiB. Anything the SDK might derive from a response (OAuth discovery, a redirect target) cannot reach another host.
  • The bearer is the exchanged OBO token or the service token, never the job token or the subject token.
  • maxRetries: 0 on reconnection; the timeout is GATEWAY_MCP_TIMEOUT_MS (default 60 000).
  • client.request is used instead of listTools/callTool because those would compile the upstream's untrusted outputSchema with ajv.
  • Every abort source is combined: the job dropped (revoke, expiry), the kill switch, the client cancelling.

Identity for MCP calls​

ConstantValue
TOKEN_EXCHANGE_GRANTurn:ietf:params:oauth:grant-type:token-exchange
ACCESS_TOKEN_TYPEurn:ietf:params:oauth:token-type:access_token
DEFAULT_EXCHANGE_TIMEOUT_MS5000
EXCHANGED_TOKEN_SKEW_MS30 000 (exchanged tokens dropped this long before expiry)
Cache keyJSON.stringify([audience, sortedScopes]) (M3: different scopes never share a token)

The token endpoint call uses HTTP Basic client authentication (form-encoded id and secret), redirect: 'error', and maps any failure to ExchangeDeniedError (idp_denied, idp_error, timeout, aborted, network, invalid_response); there is no fallback to a service identity. Without the three GATEWAY_IDP_* variables every exchange and service token is denied. Real Zitadel parameter names are UNVERIFIED (plan U1, U5).

Sources​

  • packages/agent-mcp/src/schema.ts (MCPServerConfig, RegistryTool, RegistryErrorCode)
  • packages/agent-mcp/src/loader.ts (loadRegistry, endpointProblem, MAX_REGISTRY_FILE_BYTES)
  • packages/agent-mcp/src/catalog.ts (compileCatalog, exposedName, schemaSha256, usesPattern, stripAnnotations, tooDeep, MAX_JSON_DEPTH)
  • apps/gateway/src/mcp/route.ts (mcpRoute, wrapResult, MCP_ARGS_MAX_BYTES, DROPPED_HEADERS)
  • apps/gateway/src/mcp/upstream.ts (withUpstream, pinnedFetch, MCP_RESULT_MAX_BYTES)
  • apps/gateway/src/identity/token-exchanger.ts, apps/gateway/src/identity/subject-token-cache.ts
  • apps/gateway/src/control.ts (catalog compile at registration), apps/gateway/policies/README.md, apps/gateway/Dockerfile
  • .omc/plans/p2g-governance-gateway.md sections 8.1 to 8.3, 11 and 12