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):
| Field | Type and rule |
|---|---|
id | ^[a-z][a-z0-9-]{0,63}$ |
transport | only http ("unsupported in P2.G" otherwise) |
endpoint | URL; see endpoint rules below |
enabled | boolean; disabled servers provide no tools |
allowedAgents | role policy ids allowed to use this server (exact names) |
permissions.tools[] | RegistryTool entries |
identity | mode (obo or service), audience (exact), scopes (exact names) |
RegistryTool (strict):
| Field | Rule |
|---|---|
name | gateway tool name, ToolName regex (knowledge.search style, no wildcards) |
upstreamName | ^[A-Za-z0-9_.-]{1,128}$, the tool's name on the upstream server |
description | 1 to 2048 chars; shown to the model wrapped as untrusted; the upstream's own description is never forwarded |
scopes | exact names; must be covered by the server identity's scopes |
schemaSha256 | 64 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; plainhttp:only for127.0.0.1under the test flag (GATEWAY_TEST_UPSTREAM=1withNODE_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
| Check | Response | Audit reason (kind = tool) |
|---|---|---|
| kill switch on or unreadable | 503 api_error | disabled |
| ledger read throws | 401 | ledger_error |
| row missing or settled (registration revoked) | 401 registration_stale | registration_stale |
body over 1 MiB (MCP_BODY_MAX_BYTES) | 413 | body_too_large |
| body not received in time | 408 | client_aborted |
JSON-RPC batch (first non-whitespace byte is [) | 400 | invalid_json |
arguments nested deeper than MAX_JSON_DEPTH (64) | JSON-RPC error | args_invalid |
| tool not in the catalog | JSON-RPC error, no upstream request of any kind | tool_not_granted |
tool in requireApproval | JSON-RPC error | tool_not_granted |
arguments over MCP_ARGS_MAX_BYTES (256 KiB) | JSON-RPC error | args_too_large |
| identity mode mismatch, no subject bound, exchange failed | JSON-RPC error | exchange_denied |
| upstream schema missing, changed, or uses a refused keyword | JSON-RPC error | schema_changed |
| ajv refuses the schema or the arguments do not validate | JSON-RPC error | args_invalid |
upstream response over MCP_RESULT_MAX_BYTES (1 MiB) | JSON-RPC error | result_too_large |
| upstream sent a server-to-client request | JSON-RPC error | server_request_denied |
upstream timeout (GATEWAY_MCP_TIMEOUT_MS) or error | JSON-RPC error, decision allow | upstream_timeout, upstream_error |
success with non-text blocks or structuredContent | result (text only) | content_stripped (decision allow) |
resources/*, prompts/*, any other method | MethodNotFound | method_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
| Helper | Behaviour |
|---|---|
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 </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:
Clientdeclares no capabilities (no sampling, elicitation or roots). ItsfallbackRequestHandlerrejects any server-to-client request and marks the session failed even if the upstream then answers normally.pinnedFetchonly reaches the endpoint's origin (scheme, host, port), setsredirect: '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: 0on reconnection; the timeout isGATEWAY_MCP_TIMEOUT_MS(default 60 000).client.requestis used instead oflistTools/callToolbecause those would compile the upstream's untrustedoutputSchemawith ajv.- Every abort source is combined: the job dropped (revoke, expiry), the kill switch, the client cancelling.
Identity for MCP calls
| Constant | Value |
|---|---|
TOKEN_EXCHANGE_GRANT | urn:ietf:params:oauth:grant-type:token-exchange |
ACCESS_TOKEN_TYPE | urn:ietf:params:oauth:token-type:access_token |
DEFAULT_EXCHANGE_TIMEOUT_MS | 5000 |
EXCHANGED_TOKEN_SKEW_MS | 30 000 (exchanged tokens dropped this long before expiry) |
| Cache key | JSON.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.tsapps/gateway/src/control.ts(catalog compile at registration),apps/gateway/policies/README.md,apps/gateway/Dockerfile.omc/plans/p2g-governance-gateway.mdsections 8.1 to 8.3, 11 and 12