diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f7f7152..ba7012f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,28 +43,37 @@ `retention` are now fields of the loop contract: on `llm.chat` they need `tools`, and on `llm.stream` any of them is a 400. A loop turn needs `llm.transcript.store`; the sample configuration sets `memory`. -3. **The MCP binding: `extensions/mcp-binding/`, one composable route per allowlisted MCP tool (RFC-0011 / ADR-0033, - build plan step 4).** A polyglot function host on the official MCP SDK (`@modelcontextprotocol/sdk`, a dev dependency - of this repository and the app's own dependency outside it). Servers are named in `resources/mcp-servers.yml`, each with - its transport (`stdio` with a command this process starts, or `http` with a streamable HTTP URL), its credential - references (`${VAR}` placeholders resolved from the environment at boot, never logged; a stdio subprocess gets the - SDK's minimal environment plus the variables listed), and its allowlist mapping each remote tool name to a route and - the SHA-256 digest of the tool's input schema in canonical JSON. Boot connects every server before the host listens, - lists its tools, and refuses to start - by name - when an allowlisted tool is missing or its schema no longer matches - the digest, so a server-side change stops a deploy instead of reaching a model at run time. A route's body is the - tool's arguments; its reply is the server's structured content, else the text of its content blocks; a result marked - `isError` is a 400 carrying the server's text (the agent loop returns it to the model as that call's error), a slow - call a 408, a protocol failure a 502, a lost connection a 503. `node mcp-binding.mjs describe [server]` prints each - tool's digest and a catalog row for the graph, for the developer to review: the model reads the graph's descriptions, - never the server's. `mcp.health` reports each server and its connection. The shared vector file - `test/vectors/mcp-binding-vectors.json` (the Python twin runs the same bytes) pins the digest, the allowlist - verification and the result mapping; the rest of the tests drive a fixture MCP server of this repository over both - transports. Every bound route is an alias of one `preload` function, `mcp.tool` (private, bound to no tool), registered - at boot with the server's `instances`; the function reads the route it was called as from its execution context - (`getTrace().route`). **With it, `Platform` gains `onStartup(callback)`, `onCleanup(callback)` and `shutdown()`** - async - callbacks run before the host listens and at shutdown (SIGINT and SIGTERM are handled only when a cleanup callback is - registered), the place for an extension's asynchronous boot work; the routes a callback registers are announced with - the others. **Upgrade note:** none - nothing changes for an application that registers no callback. +3. **The MCP binding: `extensions/mcp-binding/`, a composable function per MCP tool (RFC-0011 / ADR-0033, build plan + step 4; the declaration shape of the engines' `draft-design-specs/agent-tool-use.md`, 2026-11-16)** - in lockstep with + the Python pack. A library and a function host on the official MCP SDK (`@modelcontextprotocol/sdk`, a dev dependency + of this repository and the app's own dependency outside it). A tool of an MCP server is declared where every route is + declared, in the code: `const render = bind('mermaid', 'validate_and_render_mermaid_diagram', { schemaSha256: '5ae6…' })` + names the server, the remote tool and the SHA-256 digest of its input schema in canonical JSON and returns the tool as + an async function, and an ordinary `preload` function (`mermaid.render`) calls it - passing the arguments through, + shaping them or adding behaviour around the call. A route names the capability, never the transport: a tool may start + as an MCP tool and later be implemented another way, and the graph must not know. Servers are named in + `resources/mcp-servers.yml`, each with what is environment-specific: its transport (`stdio` with a command this process + starts, or `http` with a streamable HTTP URL), its credential references (`${VAR}` placeholders resolved from the + environment at boot, never logged; a stdio subprocess gets the SDK's default environment plus the variables listed) and + its call timeout. Boot connects every server a function binds a tool of, before the host listens, lists its tools and + refuses to start - by name - when a bound server is not configured, a bound tool is missing or its schema no longer + matches the pinned digest, so a server-side change stops a deploy instead of reaching a model at run time; a configured + server nobody binds is not connected. A function's body is the tool's arguments (a map, else a 400); its reply is the + server's structured content, else the text of its content blocks; a result marked `isError` is a 400 carrying the + server's text (the agent loop returns it to the model as that call's error), a slow call a 408, a protocol failure a 502, + a server not connected a 503. `node mcp-binding.mjs describe [server]` prints each tool's digest, the `bind` line to + paste and a catalog row for the graph, for the developer to review: the model reads the graph's descriptions, never the + server's. `mcp.health` reports each connected server and how many tools its functions bind. Out of the box the default + server file names the public Mermaid Chart MCP endpoint and the extension's `mermaid.render` binds its one tool, so the + binding starts and serves a tool with no credential. The shared vector file `test/vectors/mcp-binding-vectors.json` + (version 2; the Python twin runs the same bytes) pins the digest, the verification of declared bindings and the result + mapping; the rest of the tests drive a fixture MCP server of this repository over both transports. The first shape of + this binding (built 2026-11-14, before any release) read a `tools` allowlist under each server and registered each + tool's route at boot as an alias of a private `mcp.tool` function; it is gone, and a leftover `tools` key is refused by + name. **With it, `Platform` gains `onStartup(callback)`, `onCleanup(callback)` and `shutdown()`** - async callbacks run + before the host listens and at shutdown (SIGINT and SIGTERM are handled only when a cleanup callback is registered), the + place for an extension's asynchronous boot work; the routes a callback registers are announced with the others. + **Upgrade note:** none - nothing changes for an application that registers no callback. 4. **Route aliases: `preload` takes one route name or a comma-separated list** - in lockstep with the Python pack. `preload('hello.declarative, hello.world', { instances: 10 }, handler)` registers the same function under every name with the same `instances` and visibility - the Java engine's `@PreLoad(route = "a.b, c.d")` and the Rust port's diff --git a/extensions/mcp-binding/README.md b/extensions/mcp-binding/README.md index 83fc1ea0..8b9030dc 100644 --- a/extensions/mcp-binding/README.md +++ b/extensions/mcp-binding/README.md @@ -1,13 +1,19 @@ # The MCP binding -A polyglot function host that serves the tools of [MCP](https://modelcontextprotocol.io) servers as composable routes, -one route per allowlisted remote tool - adapter family B of the AI agent orchestration concept, built as step 4 of -RFC-0011 / ADR-0033 (the agent loop). A graph's agent loop (`llm.run` in the engines) names a route in its tool -catalog; the engine reaches the route through declarative Event-over-HTTP like any other function; this app issues -`tools/call` to the server behind it and returns the result. The engines stay MCP-free: a stdio server runs as a -subprocess of this process, never of an engine, and the server's credentials stay in this process's environment. - -The client library is the official MCP SDK (`@modelcontextprotocol/sdk` on npm). The Python twin (mercury-python +A library and a function host that serves the tools of [MCP](https://modelcontextprotocol.io) servers as composable +functions, one `preload` function per tool, bound in code to the remote tool through the binding's encapsulated MCP +client - adapter family B of the AI agent orchestration concept, built as step 4 of RFC-0011 / ADR-0033 (the agent loop) +and reshaped by the engines' design spec `draft-design-specs/agent-tool-use.md` (2026-11-16). A graph's agent loop +(`llm.run` in the engines) names a route in its tool catalog; the engine reaches the route through declarative +Event-over-HTTP like any other function; the function here issues `tools/call` to the server behind it and returns the +result. The engines stay MCP-free: a stdio server runs as a subprocess of this process, never of an engine, and the +server's credentials stay in this process's environment. + +The principle: **a tool is a composable function**, whatever stands behind it. A route names the capability, never the +transport (`mermaid.render`, not `mcp.mermaid.render`), because a tool may start as an MCP tool and later be implemented +another way, and the graph must not know. + +The client library is the official MCP SDK (`@modelcontextprotocol/sdk`). The Python twin (mercury-python `extensions/mcp-binding`) speaks the same contract, and both are pinned by the shared vector file `test/vectors/mcp-binding-vectors.json`. @@ -21,86 +27,105 @@ node extensions/mcp-binding/mcp-binding.mjs # the same without mercury- ``` The binding reads `resources/application.yml` next to `mcp-binding.mjs`, whichever directory the command runs from; -`-Dkey=value` overrides any key. It listens on port 8089 by default (`rest.server.port`). With no server configured -it starts and serves no tool route. +`-Dkey=value` overrides any key. It listens on port 8089 by default (`rest.server.port`). Out of the box it serves one +tool: `mermaid.render`, bound to the public Mermaid Chart MCP endpoint named in the default server file, which needs no +credential. Its log ends with `MCP server mermaid: tool validate_and_render_mermaid_diagram bound`. -To use it outside this repository, copy `mcp-binding.mjs` and its `resources` folder into your project, -`npm install mercury-composable @modelcontextprotocol/sdk`, and run `npx mercury-serve mcp-binding.mjs` (the app -imports `mercury-composable` by name, so the same file works in both places). The published package does not depend -on the SDK: the SDK is the app's dependency, not the package's. +To use it outside this repository, copy `mcp-binding.mjs` and its `resources` folder into your project, run +`npm install mercury-composable @modelcontextprotocol/sdk`, declare your tools in the copy, and start it with +`npx mercury-serve mcp-binding.mjs` (the app imports `mercury-composable` by name). + +## Declare a tool + +A tool is declared where every route is declared, in the code of `mcp-binding.mjs` (or of an application that imports +`bind` from it): + +```javascript +const render = bind('mermaid', 'validate_and_render_mermaid_diagram', + { schemaSha256: '5ae6d75d4ecfab919d9ef934bd679605bdbfc8b90b4d46f4d9dbd54d19c275ad' }); + +preload('mermaid.render', { instances: 10 }, async (_headers, body) => render(body)); +``` + +- **`bind(server, tool, { schemaSha256 })`** names the server as the server file names it, the remote tool and the + SHA-256 digest of the tool's input schema (`describe` prints it), and returns the tool as an async function: the + arguments in, the result out, with the contract below. +- **The function is ordinary.** It may pass the arguments through, shape them, or add behaviour around the call; it is + public or private like any function, and its `instances` are its own. +- **Boot verifies every declaration** before the host listens (the platform's startup hook): it connects every server a + function binds a tool of, lists its tools, and refuses to start - by name - when a bound server is not configured, a + bound tool is not offered, or its input schema no longer hashes to the pinned digest. A configured server nobody binds + is not connected (a warning); a tool the server offers but nothing binds is unreachable. + +Adding a tool is a server entry when the server is new, these few lines, a catalog row on the graph and an +Event-over-HTTP entry on the engine. ## The server file -`mcp.servers` names the file (default `mcp-servers.yml` in the resources folder; a relative path is read from there): +`mcp.servers` names the file (default `mcp-servers.yml` in the resources folder; a relative path is read from there). +It holds what is environment-specific, never the tools: ```yaml servers: + mermaid: + transport: http + url: 'https://chatgpt.mermaid.ai/anthropic/mcp' + timeout_ms: 20000 documents: transport: stdio command: npx args: ['-y', '@modelcontextprotocol/server-filesystem', '/srv/documents'] - tools: - read_text_file: - route: docs.read.text.file - schema_sha256: 'c6b1...' - list_directory: - route: docs.list.directory - schema_sha256: '9a0e...' tracker: transport: http url: 'https://mcp.example.internal/mcp' headers: Authorization: 'Bearer ${TRACKER_MCP_TOKEN}' timeout_ms: 20000 - tools: - create_issue: - route: tracker.create.issue - schema_sha256: '41d7...' ``` | Key | Meaning | | --- | --- | | `transport` | `stdio` (a command this process starts) or `http` (a streamable HTTP endpoint). Required. | -| `command`, `args`, `env`, `cwd` | The stdio server. The subprocess gets the SDK's minimal default environment plus the variables under `env`, each a credential reference such as `${GITHUB_TOKEN}`, resolved from this process's environment at boot. | +| `command`, `args`, `env`, `cwd` | The stdio server. The subprocess gets the SDK's default environment plus the variables under `env`, each a credential reference such as `${GITHUB_TOKEN}`, resolved from this process's environment at boot. | | `url`, `headers` | The http server and the headers it is reached with; a header value may be a reference such as `Bearer ${TOKEN}`. | | `timeout_ms` | How long one `tools/call` may take; default `mcp.call.timeout.ms` (30000), at least 1000. | -| `instances` | How many calls one route serves at once; default 10. | -| `tools` | The allowlist: each remote tool name maps to `route` (a Mercury route name, lowercase with a period) and `schema_sha256`, the digest of the tool's input schema. Required, at least one. | -Any other key is refused by name, so a misspelt setting never falls back to a default. A reference that resolves to -nothing (`${TOKEN}` with no `TOKEN` set) stops the boot by name, and a resolved value is never logged. A route may be -bound once across all servers. +Any other key is refused by name, so a misspelt setting never falls back to a default; a leftover `tools` allowlist from +the binding's first shape is refused with a pointer to the code. A reference that resolves to nothing (`${TOKEN}` with no +`TOKEN` set) stops the boot by name, and a resolved value is never logged. ### Digests: the server cannot change a tool under the graph A graph's catalog row carries the tool's description and input schema, written on the graph and certified with it, and -the model reads the graph's text, never the server's. The digest ties the two together: `schema_sha256` is the SHA-256 of -the tool's input schema in canonical JSON (keys sorted, no spaces, Unicode kept). At boot the binding lists each server's -tools and refuses to start when an allowlisted tool is missing or its schema no longer hashes to the pinned digest, so a -server-side change stops a deploy with its reason instead of becoming run-time errors a model improvises around. Print -the digests, and a catalog row to review before the graph carries it, with: +the model reads the graph's text, never the server's. The digest ties the two together: `schemaSha256` is the SHA-256 of +the tool's input schema in canonical JSON (keys sorted, no spaces, Unicode kept), pinned next to the function that binds +the tool. At boot the binding lists each server's tools and refuses to start when a bound tool is missing or its schema +no longer hashes to the pinned digest, so a server-side change stops a deploy with its reason instead of becoming +run-time errors a model improvises around. Print the digests, the `bind` line to paste and a catalog row to review before +the graph carries it, with: ```bash -node extensions/mcp-binding/mcp-binding.mjs describe documents +node extensions/mcp-binding/mcp-binding.mjs describe mermaid ``` ```text -# MCP server documents (stdio) offers 14 tool(s) +# MCP server mermaid (http) offers 1 tool(s) -## read_text_file - bound as docs.read.text.file (digest ok) -schema_sha256: c6b1... -catalog row (review the description before the graph carries it): +## validate_and_render_mermaid_diagram - bound (digest ok) +schema_sha256: 5ae6d75d4ecfab919d9ef934bd679605bdbfc8b90b4d46f4d9dbd54d19c275ad +bind('mermaid', 'validate_and_render_mermaid_diagram', { schemaSha256: '5ae6d75d…' }) +catalog row (name your function's route; review the description before the graph carries it): { - "name": "read_text_file", - "route": "docs.read.text.file", + "name": "validate_and_render_mermaid_diagram", + "route": "", "description": "...", "input_schema": { ... } } ``` -A tool the server offers but the allowlist omits is shown as `not allowlisted` and is never served. +A tool the server offers but no function binds is shown as `not bound` and is never served. -## The route contract +## The function contract | | | | --- | --- | @@ -109,55 +134,49 @@ A tool the server offers but the allowlist omits is shown as `not allowlisted` a | 400 | The server marked the result an error (`isError`): the reply carries the server's text. The agent loop returns it to the model as that call's error, so the model reads it and chooses another step. | | 408 | The server did not answer within `timeout_ms`. | | 502 | The server answered outside the protocol, or the SDK reported a protocol error. | -| 503 | The server is not connected (its process ended, or the endpoint is gone). | +| 503 | The server is not connected (its process ended, the endpoint is gone, or the binding has not booted). | -The routes are ordinary composable functions: a Java or Rust engine maps them in its `yaml.event.over.http` file to this -app's `/api/event`, and a graph's catalog row names the route: +The functions are ordinary composable functions: a Java or Rust engine maps them in its `yaml.event.over.http` file to +this app's `/api/event`, and a graph's catalog row names the route - or a function of the engine application calls it and +adds business logic of its own, as the Java Playground's `diagram.render` does in front of `mermaid.render`: ```yaml event: http: - - route: 'docs.read.text.file' + - route: 'mermaid.render' target: 'http://127.0.0.1:8089/api/event' ``` ```json -{ "name": "read_text_file", "route": "docs.read.text.file", "strict": true, - "description": "Read a document of the store's policy folder by its path.", - "input_schema": { "type": "object", "properties": { "path": { "type": "string" } }, "required": ["path"] } } +{ "name": "render_diagram", "route": "mermaid.render", "strict": true, + "description": "Validate a Mermaid diagram and render it as SVG.", + "input_schema": { "type": "object", "properties": { "diagramCode": { "type": "string" } }, "required": ["diagramCode"] } } ``` -One client per server is shared by its routes for the life of the process. The health route -`mcp.health` (the `/health` actuator, `mandatory.health.dependencies`) reports each server, its transport, its tool count -and whether it is connected, and answers 503 naming a server whose session is gone. - -Every bound route is served by one function, `mcp.tool`, declared with `preload` like any composable function and private: -the host answers 403 for it on the wire, and it is bound to no tool. At boot, once a server's allowlist is verified, the -binding registers each allowlisted tool's route as an alias of that function - `registry.register(route, tool, { instances })`, -the pack's counterpart of the engines' `Platform.register`, with the server's `instances` - so every route is a service of -its own, with its own mailbox and workers. A call learns the route it was addressed to from its execution context -(`getTrace().route`, the pack's counterpart of the engines' read-only `my_route` header), which names the server and the -remote tool; a call to `mcp.tool` by its own name is a 404. - -**Tracing.** A trace names the bound route, never `mcp.tool`: every trace field comes from the service entry the event -was addressed to, so the route's own record, the execution context's route, the reply's sender and the host's `Handled` -log line all read `diagram.render.mcp`. A traced call from an engine leaves the records a Java or Rust callee leaves (the -pack's guide `docs/guides/config-logging-actuators.md`): the edge's round trip `http.request` (`POST /api/event`), -parented onto the engine function that called; `event.api.service` under it; and the route's round-trip record under -that, carrying the execution's span, its `exec_time` and the `round_trip` - the MCP server's `tools/call` is inside that -`exec_time`, not a span of its own. Driven live through the Java Playground's `diagram-assistant` graph on 2026-11-14, -the lineage is continuous from the engine's `diagram.render` into this route; the record is the engines' +One client per server is shared by the functions bound to it, for the life of the process. The health route +`mcp.health` (the `/health` actuator, `mandatory.health.dependencies`) reports each connected server, its transport, how +many tools its functions bind and whether it is connected, and answers 503 naming a server whose connection is gone. + +**Tracing.** A trace names the function's route, as for any function: the route's own record, the execution context's +route (`getTrace().route`), the reply's sender and the host's `Handled` log line all read `mermaid.render`. A traced call +from an engine leaves the records a Java or Rust callee leaves (the pack's guide `docs/guides/config-logging-actuators.md`): +the edge's round trip `http.request` (`POST /api/event`), parented onto the engine function that called; +`event.api.service` under it; and the route's round-trip record under that, carrying the execution's span, its +`exec_time` and the `round_trip` - the MCP server's `tools/call` is inside that `exec_time`, not a span of its own. Driven +live through the Java Playground's `diagram-assistant` graph on 2026-11-14 (under the route's earlier name), the lineage +is continuous from the engine's `diagram.render` into this function; the record is the engines' `docs/test-reports/agent-loop-trace-lineage.md`. ## Security - **No engine runs a child process.** The MCP client, the subprocess and the credentials live here, in the pack, behind the engine's Event-over-HTTP map (the agent loop's design spec in the mercury-composable repository, - `draft-design-specs/llm-helper-agent-loop.md`, section 9). + `draft-design-specs/llm-helper-agent-loop.md`, section 9, and `draft-design-specs/agent-tool-use.md`). - **Credentials are references**, resolved from the environment at boot and never logged. The subprocess receives the - SDK's minimal default environment plus the variables listed, not this process's whole environment. -- **The allowlist is the surface.** A tool that is not listed is not served; a listed tool whose schema changed is not - served either, until the digest is reviewed and updated. + SDK's default environment plus the variables listed, not this process's whole environment. +- **The bindings in the code are the surface.** A tool no function binds is not served; a bound tool whose schema changed + is not served either, until the digest is reviewed and updated. What an application can reach is read in its code and + certified with it. - **The model never reads the server's descriptions.** The catalog row on the graph is the developer's text, reviewed through `describe`, so injection through a tool description is closed by construction. @@ -168,8 +187,8 @@ npm install && npm run build node --test test/mcp-binding.test.mjs ``` -The shared vector file pins the pure half (the digest, the allowlist verification, the result mapping) in both packs; -the rest of the tests drive a small MCP server of this repository (`test/fixtures/mcp-test-server.mjs`, on the official -SDK) over stdio and over streamable HTTP: the boot that registers one route per tool and fails fast by name, the calls, -the credential references that reach the subprocess and never a log, the health route, the describe output, and the -platform's startup hook that runs the boot before the host listens. +The shared vector file pins the pure half (the digest, the verification of declared bindings, the result mapping) in +both packs; the rest of the tests drive a small MCP server of this repository (`test/fixtures/mcp-test-server.mjs`, on +the official SDK) over stdio and over streamable HTTP: the boot that verifies every binding and fails fast by name, the +calls through functions that bind the fixture's tools, the credential references that reach the subprocess and never a +log, the health route, the describe output, and the platform's startup hook that runs the boot before the host listens. diff --git a/extensions/mcp-binding/mcp-binding.mjs b/extensions/mcp-binding/mcp-binding.mjs index c2fc7398..7d9a2e7a 100644 --- a/extensions/mcp-binding/mcp-binding.mjs +++ b/extensions/mcp-binding/mcp-binding.mjs @@ -1,11 +1,25 @@ /** - * The MCP binding - a polyglot function host that serves the tools of MCP servers as composable - * routes, one route per allowlisted remote tool (RFC-0011 / ADR-0033, section 9 of the agent - * loop's design spec). The engines stay MCP-free: a graph's agent loop (`llm.run`) names a route in - * its tool catalog, the engine reaches it through declarative Event-over-HTTP like any other - * function, and this app issues `tools/call` to the server behind it. A stdio server runs as a - * subprocess of this process, never of an engine, and its credentials stay in this process's - * environment. + * The MCP binding - a library and a function host that serves the tools of MCP servers as composable + * functions, one preload function per tool, bound in code to the remote tool through this module's + * encapsulated MCP client (RFC-0011 / ADR-0033; the engines' draft-design-specs/agent-tool-use.md). + * The engines stay MCP-free: a graph's agent loop (`llm.run`) names a route in its tool catalog, the + * engine reaches it through declarative Event-over-HTTP like any other function, and the function + * here issues `tools/call` to the server behind it. A stdio server runs as a subprocess of this + * process, never of an engine, and its credentials stay in this process's environment. + * + * A tool is declared where every route is declared - in the code: + * + * const render = bind('mermaid', 'validate_and_render_mermaid_diagram', { schemaSha256: '5ae6d75d...' }); + * preload('mermaid.render', { instances: 10 }, async (_headers, body) => render(body)); + * + * bind names the server (as the server file names it), the remote tool and the SHA-256 digest of + * the tool's input schema, and returns the tool as an async function. Boot connects every server a + * function binds a tool of, lists its tools and verifies every binding before the host listens: a + * server that is not configured, a tool the server does not offer or an input schema whose digest + * differs from the pinned one stops the application by name, so a server-side change stops a deploy + * instead of becoming run-time errors a model improvises around. A route names the capability, + * never the transport: a tool may start as an MCP tool and later be implemented another way, and + * the graph must not know. * * Run: npm install --save-dev @modelcontextprotocol/sdk (or: npm install @modelcontextprotocol/sdk) * node dist/src/cli.js extensions/mcp-binding/mcp-binding.mjs @@ -13,14 +27,11 @@ * Servers are named in resources/mcp-servers.yml (the mcp.servers key of application.yml names * the file): each has its transport (stdio with a command, or http with a URL), its credential * references (${ENV_VAR} placeholders, resolved from this process's environment at boot and never - * logged), and its allowlist mapping each remote tool to a route with the SHA-256 digest of the - * tool's input schema. Boot fails fast when an allowlisted tool is missing from tools/list or its - * schema no longer matches the digest, so a server-side change stops a deploy instead of becoming - * run-time errors a model improvises around. + * logged) and its call timeout - what is environment-specific. The tools are in the code. * * node extensions/mcp-binding/mcp-binding.mjs describe [server ...] * - * prints each server's tools with their digests and a catalog row to paste onto the graph, for the + * prints each server's tools with their digests, the bind line to paste and a catalog row for the * developer to review: the model sees the graph's descriptions, never the server's. * * The Python twin (mercury-python extensions/mcp-binding) speaks the same contract, and both are @@ -34,9 +45,7 @@ import YAML from 'yaml'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; -import { - AppException, appConfig, defaultRegistry, getLogger, getTrace, loadConfig, platform, preload, validateRoute, VERSION -} from 'mercury-composable'; +import { AppException, appConfig, getLogger, loadConfig, platform, preload, VERSION } from 'mercury-composable'; const defaultLog = getLogger('mcp-binding'); @@ -49,18 +58,16 @@ export const MIN_CALL_TIMEOUT_MS = 1000; export const TRANSPORT_STDIO = 'stdio'; export const TRANSPORT_HTTP = 'http'; export const TRANSPORTS = [TRANSPORT_STDIO, TRANSPORT_HTTP]; -export const SERVER_KEYS = ['transport', 'command', 'args', 'env', 'cwd', 'url', 'headers', 'timeout_ms', - 'instances', 'tools']; -export const TOOL_KEYS = ['route', 'schema_sha256']; +export const SERVER_KEYS = ['transport', 'command', 'args', 'env', 'cwd', 'url', 'headers', 'timeout_ms']; // the MCP specification's recommendation for a tool name const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/; const DIGEST = /^[0-9a-f]{64}$/; -// the API-safe name a graph's catalog row may use for a route, derived for the describe output +// the API-safe name a graph's catalog row may use, derived for the describe output const API_SAFE = /[^a-zA-Z0-9_-]/g; // the SDK's request timeout error code const REQUEST_TIMEOUT = -32001; -/** A configuration or boot failure: the application must not start. */ +/** A declaration, configuration or boot failure: the application must not start. */ export class BindingError extends Error { constructor(message) { super(message); @@ -95,24 +102,25 @@ export function schemaDigest(schema) { } /** - * Match the allowlist against the tools a server offers (tools/list as plain maps with name, - * description and input_schema). Every allowlisted tool must be offered and its input schema must - * hash to the pinned digest; the first failure names the tool. + * Match the tools bound to a server ({ server, tool, schema_sha256 } in declaration order) against + * the tools it offers (tools/list as plain maps with name, description and input_schema). Every + * bound tool must be offered and its input schema must hash to the pinned digest; the first + * failure, in declaration order, names the tool. */ -export function verify(spec, offered) { +export function verify(server, bindings, offered) { const byName = new Map(offered.map((tool) => [String(tool.name), tool])); const bound = []; - for (const binding of spec.tools) { - const tool = byName.get(binding.name); + for (const binding of bindings) { + const tool = byName.get(binding.tool); if (!tool) { const names = [...byName.keys()].sort(); - throw new BindingError(`MCP server ${spec.name} does not offer the tool ${binding.name} - ` + throw new BindingError(`MCP server ${server} does not offer the tool ${binding.tool} - ` + `it offers ${names.length ? names.join(', ') : 'no tools'}`); } const digest = schemaDigest(tool.input_schema); if (digest !== binding.schema_sha256) { - throw new BindingError(`MCP server ${spec.name} changed the input schema of ${binding.name} - ` - + `its digest is now ${digest}, the configuration pins ${binding.schema_sha256}`); + throw new BindingError(`MCP server ${server} changed the input schema of ${binding.tool} - ` + + `its digest is now ${digest}, the binding pins ${binding.schema_sha256}`); } bound.push({ binding, tool }); } @@ -120,7 +128,7 @@ export function verify(spec, offered) { } /** - * The reply of a route from a CallToolResult as a plain map (content, structured_content, + * The reply of a function from a CallToolResult as a plain map (content, structured_content, * is_error): the structured content when the server gives it, else the text of the content blocks * joined by newlines; a result marked is_error is a 400 carrying the server's text, which the agent * loop returns to the model as that call's error. @@ -162,7 +170,7 @@ export function toolAsPlain(tool) { return { name: tool.name, description: tool.description ?? '', input_schema: tool.inputSchema }; } -// --- configuration ---------------------------------------------------------------------- +// --- configuration: the servers ---------------------------------------------------------- function resolveValue(value) { return typeof value === 'string' ? appConfig().resolveText(value) : value; @@ -184,50 +192,14 @@ function stringMap(server, key, value) { return resolved; } -function toolsOf(server, value) { - if (!isMap(value) || Object.keys(value).length === 0) { - throw new BindingError(`MCP server ${server}: tools must map at least one remote tool name to its route and digest`); - } - const bindings = []; - const routes = new Set(); - for (const [name, item] of Object.entries(value)) { - if (!TOOL_NAME.test(name)) { - throw new BindingError(`MCP server ${server}: '${name}' is not a tool name (letters, digits, '_', '.' and '-', up to 128)`); - } - if (!isMap(item)) { - throw new BindingError(`MCP server ${server}: tool ${name} must be a map with route and schema_sha256`); - } - const unknown = Object.keys(item).filter((k) => !TOOL_KEYS.includes(k)).sort(); - if (unknown.length) { - throw new BindingError(`MCP server ${server}: tool ${name} has unknown keys ${unknown.join(', ')} - the keys are route and schema_sha256`); - } - let route; - try { - route = validateRoute(String(item.route ?? '')); - } catch (e) { - throw new BindingError(`MCP server ${server}: tool ${name}: ${e.message}`); - } - if (routes.has(route)) { - throw new BindingError(`MCP server ${server}: the route ${route} is bound twice`); - } - routes.add(route); - const digest = String(item.schema_sha256 ?? '').toLowerCase(); - if (!DIGEST.test(digest)) { - throw new BindingError(`MCP server ${server}: tool ${name} needs schema_sha256, the 64-hex digest of its input schema ` - + `- run 'node mcp-binding.mjs describe ${server}' to print it`); - } - bindings.push({ name, route, schema_sha256: digest }); - } - return bindings; -} - function serverOf(name, value, defaultTimeoutMs) { if (!isMap(value)) { throw new BindingError(`MCP server ${name} must be a map`); } const unknown = Object.keys(value).filter((k) => !SERVER_KEYS.includes(k)).sort(); if (unknown.length) { - throw new BindingError(`MCP server ${name} has unknown keys ${unknown.join(', ')} - the keys are ${SERVER_KEYS.join(', ')}`); + const hint = unknown.includes('tools') ? ' - the tools are bound in the code, not in this file' : ''; + throw new BindingError(`MCP server ${name} has unknown keys ${unknown.join(', ')} - the keys are ${SERVER_KEYS.join(', ')}${hint}`); } const transport = String(value.transport ?? ''); if (!TRANSPORTS.includes(transport)) { @@ -237,8 +209,6 @@ function serverOf(name, value, defaultTimeoutMs) { if (!Number.isFinite(timeoutMs) || timeoutMs < MIN_CALL_TIMEOUT_MS) { throw new BindingError(`MCP server ${name}: timeout_ms must be at least ${MIN_CALL_TIMEOUT_MS}`); } - const instances = Number(value.instances ?? DEFAULT_INSTANCES); - const tools = toolsOf(name, value.tools); if (transport === TRANSPORT_STDIO) { const command = resolveValue(value.command); if (!command) { @@ -253,9 +223,9 @@ function serverOf(name, value, defaultTimeoutMs) { } const cwd = resolveValue(value.cwd); return { - name, transport, tools, command: String(command), args: rawArgs.map((a) => String(resolveValue(a))), + name, transport, command: String(command), args: rawArgs.map((a) => String(resolveValue(a))), env: stringMap(name, 'env', value.env), cwd: cwd === undefined || cwd === null ? undefined : String(cwd), - url: undefined, headers: {}, timeout_ms: timeoutMs, instances + url: undefined, headers: {}, timeout_ms: timeoutMs }; } const url = resolveValue(value.url); @@ -266,8 +236,8 @@ function serverOf(name, value, defaultTimeoutMs) { throw new BindingError(`MCP server ${name}: command, args, env and cwd belong to a stdio server`); } return { - name, transport, tools, command: undefined, args: [], env: {}, cwd: undefined, url: String(url), - headers: stringMap(name, 'headers', value.headers), timeout_ms: timeoutMs, instances + name, transport, command: undefined, args: [], env: {}, cwd: undefined, url: String(url), + headers: stringMap(name, 'headers', value.headers), timeout_ms: timeoutMs }; } @@ -295,20 +265,9 @@ export function loadServers(path, log = defaultLog) { throw new BindingError(`${file} must hold a 'servers' map`); } if (Object.keys(servers).length === 0) { - log.warn(`No MCP server configured in ${file} - the binding serves no tool route`); - } - const specs = Object.entries(servers).map(([name, value]) => serverOf(String(name), value, defaultTimeout)); - const routes = new Map(); - for (const spec of specs) { - for (const binding of spec.tools) { - const owner = routes.get(binding.route); - if (owner) { - throw new BindingError(`The route ${binding.route} is bound by both ${owner} and ${spec.name}`); - } - routes.set(binding.route, spec.name); - } + log.warn(`No MCP server configured in ${file} - a function that binds a tool cannot start`); } - return specs; + return Object.entries(servers).map(([name, value]) => serverOf(String(name), value, defaultTimeout)); } // --- one connection per server ----------------------------------------------------------- @@ -342,10 +301,11 @@ export async function connectClient(spec) { return client; } -/** One MCP server: its client, shared by every route of the server. */ +/** One MCP server: its client, shared by every function bound to the server. */ export class Server { - constructor(spec, connect = connectClient, log = defaultLog) { + constructor(spec, bindings = [], connect = connectClient, log = defaultLog) { this.spec = spec; + this.bindings = [...bindings]; this.connect = connect; this.log = log; this.client = undefined; @@ -360,7 +320,7 @@ export class Server { const client = await this.connect(this.spec); try { const offered = await listTools(client); - this.bound = verify(this.spec, offered); + this.bound = verify(this.spec.name, this.bindings, offered); } catch (e) { await client.close().catch(() => undefined); throw e; @@ -407,46 +367,58 @@ export class Server { } } -// --- the application: boot, the tool function, the health check and describe ----------------- +// --- the client: bind a tool, boot the servers, report the health, describe --------------------- /** - * The binding, wired to its dependencies: connect(spec) opens a server's client, registry holds - * the routes, log the logger and out(line) prints describe's output. Tests inject fakes. + * The encapsulated MCP client of an application, wired to its dependencies: connect(spec) opens a + * server's client, log the logger and out(line) prints describe's output. Tests inject fakes. */ export function createBinding({ connect = connectClient, - registry = defaultRegistry, log = defaultLog, out = (line) => console.log(line) } = {}) { const servers = new Map(); - // what each bound route serves - the server and the allowlisted tool - filled at boot - const routes = new Map(); - - /** The server and the allowlisted tool behind a bound route; a 404 for any other route. */ - function bound(route) { - const found = routes.get(route ?? ''); - if (!found) { - throw new AppException(404, `No MCP tool is bound to the route ${route || '(none)'}`); - } - return found; - } + // every tool a function of the application binds, in declaration order + const declared = []; /** - * The one function behind every bound route. The boot registers each allowlisted tool's route - * as an alias of this function (the engines' Platform.register: one function, several routes), - * so a call learns the route it was addressed to from its execution context - getTrace().route, - * the pack's counterpart of the engines' read-only my_route header - and the route names the - * server and the remote tool. The event body is the tool's arguments, a map; the reply is the - * result as toolResult shapes it. mcp.tool itself is private and bound to no tool: it declares - * the function, and a call to it by that name is a 404. + * Declare that a function of the application serves a tool of a server: the server as the server + * file names it, the remote tool's name and the digest of its input schema (describe prints it). + * Returns the tool as an async function - the arguments in (a map, else a 400), the result out as + * toolResult shapes it; a server that is not connected is a 503. Boot verifies the declaration + * against the live server before the host listens. */ - async function tool(_headers, body) { - const { server, binding } = bound(getTrace()?.route); - if (!isMap(body)) { - throw new AppException(400, `The arguments of ${binding.name} must be a map`); + function bind(server, tool, { schemaSha256 } = {}) { + const name = String(server ?? '').trim(); + if (!name) { + throw new BindingError(`bind() needs the server's name for the tool ${tool} - the one the server file uses`); + } + if (!TOOL_NAME.test(String(tool ?? ''))) { + throw new BindingError(`'${tool}' is not a tool name (letters, digits, '_', '.' and '-', up to 128)`); } - return server.call(binding.name, body); + const digest = String(schemaSha256 ?? '').toLowerCase(); + if (!DIGEST.test(digest)) { + throw new BindingError(`The tool ${tool} of ${name} needs schemaSha256, the 64-hex digest of its input schema ` + + `- run 'node mcp-binding.mjs describe ${name}' to print it`); + } + const binding = { server: name, tool: String(tool), schema_sha256: digest }; + declared.push(binding); + const call = async (args) => { + if (!isMap(args)) { + throw new AppException(400, `The arguments of ${binding.tool} must be a map`); + } + const live = servers.get(binding.server); + if (!live) { + throw new AppException(503, `MCP server ${binding.server} is not connected`); + } + return live.call(binding.tool, args); + }; + return Object.assign(call, { server: binding.server, tool: binding.tool, declared: binding }); + } + + function declaredFor(server) { + return declared.filter((d) => d.server === server); } async function shutdown() { @@ -454,29 +426,36 @@ export function createBinding({ await server.close(); } servers.clear(); - routes.clear(); } /** - * Connect every configured server, verify its allowlist and register the routes - before the - * first request; a failure stops the application with its reason. + * Connect every server a function binds a tool of and verify every binding - before the host + * listens; a failure stops the application with its reason. */ async function boot() { try { const specs = loadServers(undefined, log); + const configured = new Set(specs.map((s) => s.name)); + for (const d of declared) { + if (!configured.has(d.server)) { + throw new BindingError(`No MCP server named ${d.server} is configured - a function binds its tool ${d.tool}`); + } + } for (const spec of specs) { - const server = new Server(spec, connect, log); + const bindings = declaredFor(spec.name); + if (!bindings.length) { + log.warn(`MCP server ${spec.name}: no function binds a tool of it - not connected`); + continue; + } + const server = new Server(spec, bindings, connect, log); await server.start(); servers.set(spec.name, server); for (const { binding } of server.bound) { - // the route is an alias of tool - the one function under the configured name, the - // engines' Platform.register shape - with the server's instances - routes.set(binding.route, { server, binding }); - registry.register(binding.route, tool, { instances: spec.instances }); - log.info(`MCP server ${spec.name}: tool ${binding.name} served as ${binding.route}`); + log.info(`MCP server ${spec.name}: tool ${binding.tool} bound`); } } - log.info(`MCP binding ready - ${servers.size} server(s), ${routes.size} route(s)`); + const bound = [...servers.values()].reduce((n, s) => n + s.bound.length, 0); + log.info(`MCP binding ready - ${servers.size} server(s), ${bound} bound tool(s)`); } catch (e) { log.error(`MCP binding cannot start - ${e.message}`); await shutdown(); @@ -486,7 +465,7 @@ export function createBinding({ /** * Health check speaking the engines' interface contract (type=info / type=health): which - * servers are configured, how many tools each serves, and whether each is connected. + * servers are connected and how many tools the functions of the application bind on each. */ async function health(headers) { if (headers.type === 'info') { @@ -505,7 +484,10 @@ export function createBinding({ return 'mcp.binding is running fine'; } - /** Print each server's tools, their input-schema digests and a catalog row for the graph. */ + /** + * Print each server's tools, their input-schema digests, the bind line that declares each and a + * catalog row for the graph. + */ async function describe(names, err = (line) => console.error(line)) { let specs; try { @@ -528,35 +510,54 @@ export function createBinding({ } finally { await client.close().catch(() => undefined); } - const configured = new Map(spec.tools.map((b) => [b.name, b])); + const bindings = new Map(declaredFor(spec.name).map((d) => [d.tool, d])); out(`# MCP server ${spec.name} (${spec.transport}) offers ${offered.length} tool(s)`); for (const tool of offered) { const digest = schemaDigest(tool.input_schema); - const bound = configured.get(tool.name); + const bound = bindings.get(tool.name); const state = bound - ? `bound as ${bound.route} ${bound.schema_sha256 === digest ? '(digest ok)' : '(DIGEST CHANGED)'}` - : 'not allowlisted'; + ? `bound ${bound.schema_sha256 === digest ? '(digest ok)' : '(DIGEST CHANGED)'}` + : 'not bound'; out(`\n## ${tool.name} - ${state}\nschema_sha256: ${digest}`); + out(`bind('${spec.name}', '${tool.name}', { schemaSha256: '${digest}' })`); const row = { name: tool.name.replace(API_SAFE, '_').slice(0, 128) || 'tool', - route: bound ? bound.route : '', + route: '', description: tool.description, input_schema: tool.input_schema }; - out('catalog row (review the description before the graph carries it):'); + out("catalog row (name your function's route; review the description before the graph carries it):"); out(JSON.stringify(row, null, 2)); } } return 0; } - return { boot, shutdown, tool, health, describe, servers, routes }; + return { bind, boot, shutdown, health, describe, servers, declared, declaredFor }; } const binding = createBinding(); -preload('mcp.tool', { instances: DEFAULT_INSTANCES, isPrivate: true }, binding.tool); +/** Declare a tool a function of this application serves - see createBinding().bind. */ +export const bind = binding.bind; + preload('mcp.health', { instances: 5, isPrivate: true }, binding.health); +// --- the functions: a tool of an MCP server is a composable function of this application ------- +// +// Declare each tool with bind(server, tool, { schemaSha256 }) - the server as the server file names +// it, the remote tool's name and the digest `describe` prints - and call it from an ordinary +// preload function, which may pass the arguments through, shape them or add behaviour around the +// call. Name the route after the capability, never the transport. + +/** + * Validate a Mermaid diagram and render it as SVG - the tool of the public Mermaid Chart MCP server + * the default server file names. The body is the tool's arguments (diagramCode); the reply is the + * server's structured result. + */ +export const renderMermaid = bind('mermaid', 'validate_and_render_mermaid_diagram', + { schemaSha256: '5ae6d75d4ecfab919d9ef934bd679605bdbfc8b90b4d46f4d9dbd54d19c275ad' }); +preload('mermaid.render', { instances: DEFAULT_INSTANCES }, async (_headers, body) => renderMermaid(body)); + const isMain = process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href; if (isMain) { // -Dkey=value arguments belong to the configuration, which reads them from process.argv itself @@ -570,7 +571,7 @@ if (isMain) { await platform.run(); } } else { - // loaded by mercury-serve: the servers connect inside the serving loop, before the first request + // loaded by mercury-serve: the servers connect inside the serving loop, before the host listens platform.onStartup(binding.boot); platform.onCleanup(binding.shutdown); } diff --git a/extensions/mcp-binding/resources/application.yml b/extensions/mcp-binding/resources/application.yml index f12d2c00..9eae1b52 100644 --- a/extensions/mcp-binding/resources/application.yml +++ b/extensions/mcp-binding/resources/application.yml @@ -5,7 +5,7 @@ # node dist/src/cli.js extensions/mcp-binding/mcp-binding.mjs -Dmcp.servers=/etc/mercury/mcp-servers.yml application.name: 'mcp-binding' -info.app.description: 'Mercury Composable MCP binding (one composable route per allowlisted MCP tool)' +info.app.description: 'Mercury Composable MCP binding (a composable function per MCP tool)' rest.server.port: 8089 diff --git a/extensions/mcp-binding/resources/mcp-servers.yml b/extensions/mcp-binding/resources/mcp-servers.yml index 46f51688..cd301fe6 100644 --- a/extensions/mcp-binding/resources/mcp-servers.yml +++ b/extensions/mcp-binding/resources/mcp-servers.yml @@ -1,38 +1,37 @@ -# MCP servers by name. A graph never carries a command line or a URL: its tool catalog names the -# ROUTE each remote tool is served as, and this file maps the route to the server and the tool. +# MCP servers by name - what is environment-specific: the transport, the credential references +# and the call timeout. The tools are not here: a tool is a function of the application, declared +# in mcp-binding.mjs with bind(server, tool, { schemaSha256 }) and served under a route of its own, +# so a graph's tool catalog names the route like any other composable function. # -# Every allowlisted tool pins the SHA-256 digest of its input schema (canonical JSON: keys sorted, -# no spaces). Boot fails when the server no longer offers the tool or its schema changed, so a -# server-side change stops a deploy instead of becoming run-time errors. Print the digests, and a -# catalog row to review and paste onto the graph, with: +# Every binding pins the SHA-256 digest of the tool's input schema (canonical JSON: keys sorted, +# no spaces). Boot fails when a bound server is not configured here, no longer offers the tool or +# changed its schema, so a server-side change stops a deploy instead of becoming run-time errors. +# Print each tool's digest and the bind line to paste with: # # node extensions/mcp-binding/mcp-binding.mjs describe [server ...] # # Credentials are references: a ${NAME} placeholder resolves from this process's environment at # boot (${NAME:default} with a default) and is never logged. A stdio server runs as a subprocess of -# this process with the SDK's minimal default environment plus the variables listed under env; an -# http server is reached at its URL with the headers listed. +# this process with the SDK's default environment plus the variables listed under env; an http +# server is reached at its URL with the headers listed. # # Keys per server: transport (stdio | http), command, args, env, cwd (stdio), url, headers (http), -# timeout_ms (per call, at least 1000; default mcp.call.timeout.ms), instances (per route, default -# 10), tools (remote tool name -> {route, schema_sha256}). Unknown keys are refused by name. +# timeout_ms (per call, at least 1000; default mcp.call.timeout.ms). Unknown keys are refused by +# name. A configured server no function binds a tool of is not connected (a warning at boot). # -servers: {} - # Replace the empty map with your servers. The samples below are the shape, not a running - # configuration: fill the digests from `describe` before starting the binding, or the boot - # refuses them by name. With no server configured the binding starts and serves no tool route. +servers: + # The public Mermaid Chart MCP endpoint, reached over streamable HTTP with no credential: the + # server behind the extension's own function mermaid.render (the Java engine's diagram-assistant + # example calls it). Replace or extend with your servers, and declare their tools in the code. + mermaid: + transport: http + url: 'https://chatgpt.mermaid.ai/anthropic/mcp' + timeout_ms: 20000 # # documents: # transport: stdio # command: npx # args: ['-y', '@modelcontextprotocol/server-filesystem', '/srv/documents'] - # tools: - # read_text_file: - # route: docs.read.text.file - # schema_sha256: '<64 hex from describe>' - # list_directory: - # route: docs.list.directory - # schema_sha256: '<64 hex from describe>' # # tracker: # transport: http @@ -40,8 +39,3 @@ servers: {} # headers: # Authorization: 'Bearer ${TRACKER_MCP_TOKEN}' # timeout_ms: 20000 - # tools: - # create_issue: - # route: tracker.create.issue - # schema_sha256: '<64 hex from describe>' - # diff --git a/memory/continuity.md b/memory/continuity.md index f26aaf83..bc7029d7 100644 --- a/memory/continuity.md +++ b/memory/continuity.md @@ -169,7 +169,24 @@ an engine change in both engines, not taken. **How to apply:** a new MCP tool for an agent is a server entry and an allowlist row here plus a catalog row on the graph, never engine code; a schema change is a digest the developer re-reviews; a credential is a reference in the server file, resolved from this process's environment. - + + +- **A tool of an MCP server is a composable function of the binding, declared in code (Eric's review 2026-11-16; the + engines' `draft-design-specs/agent-tool-use.md`; supersedes the allowlist-row shape of 2026-11-14; the twin of the + Python pack's reshaping).** `extensions/mcp-binding/mcp-binding.mjs` is a library and a function host: + `bind(server, tool, { schemaSha256 })` declares a binding and returns the tool as an async function, and an ordinary + `preload` function calls it - the extension's own `mermaid.render` binds the one tool of the public Mermaid Chart MCP + endpoint named in the default server file, so the binding serves a tool out of the box. The server file keeps what is + environment-specific (transport, command or URL, credential references, timeout) and refuses a `tools` allowlist by + name; boot connects every server a function binds a tool of, lists its tools and stops the application by name when a + bound server is not configured, a tool is not offered or its digest changed; a configured server nobody binds is not + connected. `mcp.tool` is no longer a route; `mcp.health` stays. A route names the capability, never the transport: a + tool may start as an MCP tool and later be implemented another way, and the graph must not know. The shared vectors + are version 2 (`verify_cases` over declared bindings), byte-identical with the Python twin. **How to apply:** a new + tool is a `bind` line, a few-line `preload` function, a catalog row on the graph and an Event-over-HTTP entry; a schema + change is a digest re-reviewed next to the function; a new server is a server-file entry; never a route in a YAML file + and never engine code. + - **A traced call into the pack leaves the records a Java or Rust callee leaves, so a span lineage is continuous from an engine into the pack (2026-11-14, the twin of mercury-python #53; Eric's criterion: for OpenTelemetry to be certified, diff --git a/memory/open-threads/thread-mcp-binding.md b/memory/open-threads/thread-mcp-binding.md index 586caf6c..5d0e0937 100644 --- a/memory/open-threads/thread-mcp-binding.md +++ b/memory/open-threads/thread-mcp-binding.md @@ -6,4 +6,9 @@ mercury-python #52 - is PR #119, MERGED 2026-11-14 (merge `ffadfcf`). Next: the pack's catch-up release carries it ([[pack-catch-up-4-12-25]]). Fact: [[mcp-binding-route-per-tool]]. → serves: vision-mercury-nodejs + **Reshaped 2026-11-16 (Eric's review; the engines' `draft-design-specs/agent-tool-use.md`; in lockstep with the Python + pack):** a `preload` function per tool bound in code through `bind(server, tool, { schemaSha256 })`, no generic route, + the server file servers-only, the extension's own `mermaid.render` out of the box; the shared vectors version 2 (49 + tests; the boot and a render driven live against the Mermaid server). Then the Playground calls `mermaid.render`. + Fact: [[mcp-binding-function-per-tool]]. diff --git a/memory/sessions/2026-11-16-044314.md b/memory/sessions/2026-11-16-044314.md new file mode 100644 index 00000000..8fe017c8 --- /dev/null +++ b/memory/sessions/2026-11-16-044314.md @@ -0,0 +1,49 @@ +# Session (2026-11-16T04:43:14.573Z) + +**Agent:** Claude Code +**Title:** The MCP binding reshaped: a `preload` function per tool, bound in code through an encapsulated client (the twin of the Python pack's reshaping) + +## Context + +Follows 2026-11-16-032007 (merged as #121). Eric fixed a loose end of the MCP binding before the AI SDLC work resumes: +the Playground's `diagram.render` called a pack route, `diagram.render.mcp`, that no `preload` here declared - the +server file's allowlist row conjured it at boot as an alias of the private `mcp.tool`. The design is recorded in the +engines' `draft-design-specs/agent-tool-use.md` (Eric's rulings: the function lives in the pack, bound in code; no `mcp.` +prefix on a tool's route; the engine's `DiagramRender` stays). The Python pack was reshaped first in the same working +session; this is the Node twin, in lockstep. + +## What changed (branch `feat/mcp-binding-function-per-tool`, the PR opened 2026-11-16) + +- `extensions/mcp-binding/mcp-binding.mjs`: `createBinding({ connect, log, out })` (no registry: the binding registers no + route) returns `bind`, `boot`, `shutdown`, `health`, `describe`, `servers`, `declared`; `bind(server, tool, + { schemaSha256 })` validates the declaration and returns an async function carrying `server`, `tool` and `declared` + (a non-map argument a 400, a server not connected a 503); `boot` refuses by name a binding whose server is not + configured, connects every server a function binds a tool of (a server nobody binds is warned about and skipped), and + each `Server(spec, bindings)` verifies its bindings against `tools/list` (`verify(server, bindings, offered)`, "the + binding pins"). `SERVER_KEYS` drops `instances` and `tools` (a leftover `tools` key refused with a pointer to the code); + `mcp.tool` is gone; `mcp.health` stays; `describe` prints `bound (digest ok)` / `not bound`, the `bind` line and a + catalog row whose route is the developer's. The extension's own function: `renderMermaid = bind('mermaid', + 'validate_and_render_mermaid_diagram', { schemaSha256 })` and `preload('mermaid.render', { instances: 10 }, ...)`. +- `extensions/mcp-binding/resources/mcp-servers.yml`: the `mermaid` server and commented samples, servers only; + `application.yml`: the description. +- `test/vectors/mcp-binding-vectors.json`: the Python pack's version 2 file, byte for byte (sha `b470762e…`). +- `test/mcp-binding.test.mjs` (49 tests, 46 before): the vector contracts over declared bindings; the boot that + verifies every binding and the functions calling the fixture's tools through a registry of the test's own; two + functions binding one tool; a binding to an unconfigured server and a server nobody binds; `bind` refusing a bad + declaration; the server-file checks (`tools` and `instances` refused); the example function pinned without network. +- `extensions/mcp-binding/README.md` rewritten for the shape; CHANGELOG Unreleased Added 3 rewritten. + +## Verification + +- `npm test`: 469 tests, 405 passed, 0 failed, 64 skipped (402 + 3). +- Live: `node dist/src/cli.js extensions/mcp-binding/mcp-binding.mjs` on port 8096 booted against the public Mermaid + server (`MCP server mermaid: tool validate_and_render_mermaid_diagram bound`, `MCP binding ready - 1 server(s), 1 bound + tool(s)`, `Loaded PUBLIC mermaid.render`), `/info/routes` showed `mermaid.render` public at 10 and `mcp.health` private; + a `PostOffice` RPC to `mermaid.render` with a small flowchart answered 200 with the server's structured result + (`valid: true`, the SVG), and a non-map body 400 naming the tool. The process was stopped afterwards. + +## Memory References + +- Superseded: mcp-binding-route-per-tool -> mcp-binding-function-per-tool +- Created: mcp-binding-function-per-tool (tier: working) +- Threads: mcp-binding (edited: the reshaping and the Playground step ahead) diff --git a/test/mcp-binding.test.mjs b/test/mcp-binding.test.mjs index 953bd040..eb81ed3b 100644 --- a/test/mcp-binding.test.mjs +++ b/test/mcp-binding.test.mjs @@ -2,14 +2,14 @@ * The MCP binding (extensions/mcp-binding/mcp-binding.mjs). * * The shared contract file test/vectors/mcp-binding-vectors.json (byte-identical in mercury-python) - * pins the pure half: the input-schema digest, the allowlist verification and the result mapping. - * The tests after the vector runs drive the real transports against the fixture server of - * test/fixtures (a small MCP server on the official SDK, over stdio and over streamable HTTP): the - * boot that registers one route per allowlisted tool and fails fast by name, the calls through the - * bound routes (local RPC through the bus, as the host dispatches them: every route is an alias of - * the one preload function), the credential references that reach the subprocess and never a log, - * the health route, the describe output, and the platform's startup hook that runs the boot before - * the host listens. + * pins the pure half: the input-schema digest, the verification of the tools the functions bind + * against the tools a server offers, and the result mapping. The tests after the vector runs drive + * the real transports against the fixture server of test/fixtures (a small MCP server on the + * official SDK, over stdio and over streamable HTTP): the boot that verifies every binding and + * fails fast by name, the calls through functions that bind the fixture's tools (local RPC through + * the bus, as the host dispatches them), the credential references that reach the subprocess and + * never a log, the health route, the describe output, and the platform's startup hook that runs + * the boot before the host listens. */ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; @@ -23,22 +23,17 @@ import { fileURLToPath } from 'node:url'; import YAML from 'yaml'; import { AppException, appConfig, defaultRegistry, FunctionRegistry, Platform, PostOffice } from 'mercury-composable'; import { - BindingError, connectClient, createBinding, DEFAULT_SERVERS_FILE, loadServers, schemaDigest, Server, + BindingError, connectClient, createBinding, DEFAULT_SERVERS_FILE, loadServers, renderMermaid, schemaDigest, Server, toolResult, verify } from '../extensions/mcp-binding/mcp-binding.mjs'; const VECTORS_FILE = new URL('./vectors/mcp-binding-vectors.json', import.meta.url); // the Python twin pins the same digest: change the file in both packs or in neither -const VECTORS_SHA256 = '4bacc319859847ff82e5d169ad9c0dea4ffdd6fe06883537ebf5ee66bdba907a'; +const VECTORS_SHA256 = 'b470762efe1d77145c430cb3f946956256126f3e4e53e8d001cfed35316ee6a2'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const FIXTURE = fileURLToPath(new URL('./fixtures/mcp-test-server.mjs', import.meta.url)); const FIXTURE_TOOLS = ['add', 'echo', 'env_present', 'fail', 'slow']; -function specOf(caseServer) { - const tools = Object.entries(caseServer.tools).map(([name, t]) => ({ name, route: t.route, schema_sha256: t.schema_sha256 })); - return { name: caseServer.name, transport: 'stdio', tools, command: 'x', args: [], env: {}, headers: {}, timeout_ms: 30000, instances: 10 }; -} - // --- the shared vectors ------------------------------------------------------------------- test('the vector file is the one the Python twin runs', () => { @@ -54,11 +49,12 @@ for (const c of VECTORS.digest_cases) { for (const c of VECTORS.verify_cases) { test(c.name, () => { - const spec = specOf(c.server); + const server = c.server.name; + const bindings = c.bindings.map((b) => ({ server, tool: b.tool, schema_sha256: b.schema_sha256 })); if (c.expect.error) { - assert.throws(() => verify(spec, c.offered), (e) => e instanceof BindingError && e.message === c.expect.error); + assert.throws(() => verify(server, bindings, c.offered), (e) => e instanceof BindingError && e.message === c.expect.error); } else { - assert.deepEqual(verify(spec, c.offered).map((b) => b.binding.route), c.expect.bound); + assert.deepEqual(verify(server, bindings, c.offered).map((b) => b.binding.tool), c.expect.bound); } }); } @@ -79,7 +75,7 @@ for (const c of VECTORS.result_cases) { /** A logger that keeps what it is told, so a test can assert what never reached a log. */ function ledger() { const lines = []; - const log = { + return { lines, text: () => lines.join('\n'), debug: (m) => lines.push(`DEBUG ${m}`), @@ -87,15 +83,13 @@ function ledger() { warn: (m) => lines.push(`WARN ${m}`), error: (m) => lines.push(`ERROR ${m}`) }; - return log; } /** What the fixture server offers, as the binding reads it: the digests come from the server itself. */ let offered; before(async () => { - const probe = new Server({ name: 'probe', transport: 'stdio', tools: [], command: process.execPath, args: [FIXTURE], - env: {}, headers: {}, timeout_ms: 30000, instances: 10 }, connectClient, ledger()); - const client = await connectClient(probe.spec); + const client = await connectClient({ name: 'probe', transport: 'stdio', command: process.execPath, args: [FIXTURE], + env: {}, headers: {}, timeout_ms: 30000 }); try { const page = await client.listTools(); offered = Object.fromEntries(page.tools.map((t) => [t.name, { name: t.name, description: t.description ?? '', input_schema: t.inputSchema }])); @@ -109,7 +103,7 @@ after(() => appConfig().set('mcp.servers', DEFAULT_SERVERS_FILE)); const scratch = mkdtempSync(join(tmpdir(), 'mcp-binding-')); let fileCount = 0; -/** Point the binding at a temporary server file and give the test a fresh binding with its own registry and log. */ +/** Point the binding at a temporary server file and give the test a fresh binding, a registry of its own and a log. */ function servers(entries) { const path = join(scratch, `mcp-servers-${fileCount++}.yml`); writeFileSync(path, YAML.stringify({ servers: entries }), 'utf8'); @@ -117,23 +111,26 @@ function servers(entries) { const registry = new FunctionRegistry(); const log = ledger(); const lines = []; - const app = createBinding({ registry, log, out: (line) => lines.push(line) }); + const app = createBinding({ log, out: (line) => lines.push(line) }); return { app, registry, log, lines }; } -/** A stdio server entry for the fixture, every tool with the digest the server reports. */ -function stdio(tools, extra = {}) { - const entry = { - transport: 'stdio', command: process.execPath, args: [FIXTURE], - tools: Object.fromEntries(Object.entries(tools).map(([name, route]) => [name, { route, schema_sha256: schemaDigest(offered[name].input_schema) }])) - }; - return { ...entry, ...extra }; +/** A stdio server entry for the fixture - the servers file names servers only; the tools are bound in code. */ +function stdio(extra = {}) { + return { transport: 'stdio', command: process.execPath, args: [FIXTURE], ...extra }; } /** - * Local RPC through the registry's bus, the path a request takes behind the HTTP host: the bound - * route's alias dispatches the binding's tool function with the route in its execution context. + * The documented shape: bind a tool of a server with the digest the server reports (or the one + * given), and register a function under the route that calls it - what preload does for an app. */ +function serve(app, registry, route, server, tool, { instances = 10, digest } = {}) { + const call = app.bind(server, tool, { schemaSha256: digest ?? schemaDigest(offered[tool].input_schema) }); + registry.register(route, async (_headers, body) => call(body), { instances }); + return call; +} + +/** Local RPC through the registry's bus, the path a request takes behind the HTTP host. */ async function call(registry, route, body) { assert.ok(registry.get(route), `${route} is not registered`); return new PostOffice(undefined, {}, registry).request(route, body, { timeoutMs: 10000 }); @@ -163,36 +160,57 @@ test('the fixture server has the tools the tests rely on', () => { assert.deepEqual(Object.keys(offered).sort(), FIXTURE_TOOLS); }); -test('boot registers one route per allowlisted tool and the routes call the server', async () => { - const { app, registry } = servers({ fixture: stdio({ echo: 'fixture.echo', add: 'fixture.add', fail: 'fixture.fail' }, { instances: 3 }) }); +test('the example function binds the mermaid tool out of the box', () => { + // the extension's own function: declared with preload like any route, public, bound in code + const service = defaultRegistry.get('mermaid.render'); + assert.ok(service && !service.isPrivate && service.instances === 10); + assert.deepEqual([renderMermaid.server, renderMermaid.tool], ['mermaid', 'validate_and_render_mermaid_diagram']); + assert.match(renderMermaid.declared.schema_sha256, /^[0-9a-f]{64}$/); + assert.equal(defaultRegistry.get('mcp.tool'), undefined, 'the generic route is gone - a tool is a function'); +}); + +test('boot verifies every binding and the functions call their tools', async () => { + const { app, registry } = servers({ fixture: stdio() }); + const echo = serve(app, registry, 'fixture.echo', 'fixture', 'echo', { instances: 3 }); + serve(app, registry, 'fixture.add', 'fixture', 'add'); + serve(app, registry, 'fixture.fail', 'fixture', 'fail'); await app.boot(); try { assert.deepEqual([...app.servers.keys()], ['fixture']); - assert.deepEqual(app.servers.get('fixture').bound.map((b) => b.binding.route), ['fixture.echo', 'fixture.add', 'fixture.fail']); - // the composable shape: one preload function, each bound route a public alias of it with the - // server's instances; the declared route itself is private and bound to no tool - for (const route of ['fixture.echo', 'fixture.add', 'fixture.fail']) { - const service = registry.get(route); - assert.ok(service.handler === app.tool && !service.isPrivate && service.instances === 3, route); - } - const declared = defaultRegistry.get('mcp.tool'); - assert.ok(declared && declared.isPrivate, 'mcp.tool is declared, private'); - await rejects(declared.handler({}, { text: 'no tool here' }), 404, 'No MCP tool is bound to the route (none)'); + assert.deepEqual(app.servers.get('fixture').bound.map((b) => b.binding.tool), ['echo', 'add', 'fail']); + const service = registry.get('fixture.echo'); + assert.ok(service && service.instances === 3 && !service.isPrivate); assert.equal(ok(await call(registry, 'fixture.echo', { text: 'hello' })), 'hello'); assert.deepEqual(ok(await call(registry, 'fixture.add', { a: 1, b: 2 })), { sum: 3 }); failed(await call(registry, 'fixture.fail', { reason: 'the vault is closed' }), 400, 'the vault is closed'); failed(await call(registry, 'fixture.echo', 'hello'), 400, 'must be a map'); - registry.register('mcp.tool', app.tool, { isPrivate: true }); - failed(await call(registry, 'mcp.tool', { text: 'no tool here' }), 404, 'No MCP tool is bound to the route mcp.tool'); + assert.deepEqual([echo.server, echo.tool], ['fixture', 'echo']); } finally { await app.shutdown(); } assert.equal(app.servers.size, 0); - assert.equal(app.routes.size, 0); + // the declarations are code and survive a shutdown; a call before the next boot is a 503 by name + assert.deepEqual(app.declared.map((d) => d.tool), ['echo', 'add', 'fail']); + failed(await call(registry, 'fixture.echo', { text: 'later' }), 503, 'MCP server fixture is not connected'); +}); + +test('two functions may bind the same tool', async () => { + const { app, registry } = servers({ fixture: stdio() }); + serve(app, registry, 'fixture.echo.one', 'fixture', 'echo'); + serve(app, registry, 'fixture.echo.two', 'fixture', 'echo'); + await app.boot(); + try { + assert.equal(app.servers.get('fixture').bound.length, 2); + assert.equal(ok(await call(registry, 'fixture.echo.one', { text: '1' })), '1'); + assert.equal(ok(await call(registry, 'fixture.echo.two', { text: '2' })), '2'); + } finally { + await app.shutdown(); + } }); test("a slow tool is a 408 within the server's timeout", async () => { - const { app, registry } = servers({ fixture: stdio({ slow: 'fixture.slow' }, { timeout_ms: 1000 }) }); + const { app, registry } = servers({ fixture: stdio({ timeout_ms: 1000 }) }); + serve(app, registry, 'fixture.slow', 'fixture', 'slow'); await app.boot(); try { const started = Date.now(); @@ -204,26 +222,59 @@ test("a slow tool is a 408 within the server's timeout", async () => { }); test('a missing tool fails the boot by name', async () => { - const entry = stdio({ echo: 'fixture.echo' }); - entry.tools.nope = { route: 'fixture.nope', schema_sha256: '0'.repeat(64) }; - const { app, log } = servers({ fixture: entry }); + const { app, registry, log } = servers({ fixture: stdio() }); + serve(app, registry, 'fixture.echo', 'fixture', 'echo'); + serve(app, registry, 'fixture.nope', 'fixture', 'nope', { digest: '0'.repeat(64) }); await assert.rejects(app.boot(), (e) => e instanceof BindingError && e.message.includes('does not offer the tool nope')); assert.ok(log.text().includes('does not offer the tool nope')); assert.equal(app.servers.size, 0, 'a failed boot leaves no connection behind'); }); test('a changed schema fails the boot by name', async () => { - const entry = stdio({ echo: 'fixture.echo' }); - entry.tools.echo.schema_sha256 = 'f'.repeat(64); - const { app, log } = servers({ fixture: entry }); + const { app, registry, log } = servers({ fixture: stdio() }); + serve(app, registry, 'fixture.echo', 'fixture', 'echo', { digest: 'f'.repeat(64) }); await assert.rejects(app.boot(), (e) => e instanceof BindingError && e.message.includes('changed the input schema of echo')); assert.ok(log.text().includes(schemaDigest(offered.echo.input_schema)), 'the current digest is shown'); }); +test('a binding to an unconfigured server fails the boot by name', async () => { + const { app, registry, log } = servers({ fixture: stdio() }); + serve(app, registry, 'ghost.echo', 'ghost', 'echo'); + await assert.rejects(app.boot(), (e) => e instanceof BindingError + && e.message.includes('No MCP server named ghost is configured - a function binds its tool echo')); + assert.ok(log.text().includes('No MCP server named ghost is configured')); + assert.equal(app.servers.size, 0); +}); + +test('a configured server nobody binds is not connected', async () => { + // the spare server's command does not exist: it is never started, so the boot still succeeds + const { app, registry, log } = servers({ fixture: stdio(), spare: { transport: 'stdio', command: 'no-such-mcp-server-command' } }); + serve(app, registry, 'fixture.echo', 'fixture', 'echo'); + await app.boot(); + try { + assert.deepEqual([...app.servers.keys()], ['fixture']); + assert.ok(log.text().includes('MCP server spare: no function binds a tool of it - not connected')); + } finally { + await app.shutdown(); + } +}); + +for (const [server, tool, digest, message] of [ + ['', 'echo', '0'.repeat(64), "needs the server's name"], + ['fixture', 'bad name!', '0'.repeat(64), 'is not a tool name'], + ['fixture', 'echo', 'short', 'needs schemaSha256'] +]) { + test(`bind refuses a bad declaration: ${message}`, () => { + assert.throws(() => createBinding({ log: ledger() }).bind(server, tool, { schemaSha256: digest }), + (e) => e instanceof BindingError && e.message.includes(message)); + }); +} + test('credential references reach the subprocess and never a log', async () => { process.env.FIXTURE_TOKEN = 'a-value-that-must-not-appear'; try { - const { app, registry, log } = servers({ fixture: stdio({ env_present: 'fixture.env.present' }, { env: { FIXTURE_FORWARDED: '${FIXTURE_TOKEN}' } }) }); + const { app, registry, log } = servers({ fixture: stdio({ env: { FIXTURE_FORWARDED: '${FIXTURE_TOKEN}' } }) }); + serve(app, registry, 'fixture.env.present', 'fixture', 'env_present'); await app.boot(); try { assert.deepEqual(ok(await call(registry, 'fixture.env.present', { name: 'FIXTURE_FORWARDED' })), { present: true }); @@ -240,23 +291,21 @@ test('credential references reach the subprocess and never a log', async () => { test('an unset credential reference is refused at load', () => { delete process.env.FIXTURE_MISSING_TOKEN; - servers({ fixture: stdio({ echo: 'fixture.echo' }, { env: { TOKEN: '${FIXTURE_MISSING_TOKEN}' } }) }); + servers({ fixture: stdio({ env: { TOKEN: '${FIXTURE_MISSING_TOKEN}' } }) }); assert.throws(() => loadServers(), (e) => e instanceof BindingError && e.message.includes('env.TOKEN resolves to nothing')); }); -const tool = { echo: { route: 'a.b', schema_sha256: '0'.repeat(64) } }; for (const [entry, message] of [ - [{ transport: 'ftp', tools: tool }, 'transport must be stdio or http'], - [{ transport: 'stdio', tools: tool }, 'a stdio server needs a command'], - [{ transport: 'http', tools: tool }, 'an http server needs a url'], - [{ transport: 'stdio', command: 'x', url: 'http://x', tools: tool }, 'url and headers belong to an http server'], - [{ transport: 'stdio', command: 'x', colour: 'blue', tools: tool }, 'has unknown keys colour'], - [{ transport: 'stdio', command: 'x', tools: {} }, 'tools must map at least one remote tool'], - [{ transport: 'stdio', command: 'x', tools: { echo: { route: 'NoDots', schema_sha256: '0'.repeat(64) } } }, 'Invalid route name'], - [{ transport: 'stdio', command: 'x', tools: { echo: { route: 'a.b', schema_sha256: 'short' } } }, 'needs schema_sha256'], - [{ transport: 'stdio', command: 'x', tools: { echo: { route: 'a.b', schema_sha256: '0'.repeat(64), mode: 'x' } } }, 'has unknown keys mode'], - [{ transport: 'stdio', command: 'x', timeout_ms: 10, tools: tool }, 'timeout_ms must be at least 1000'], - [{ transport: 'stdio', command: 'x', tools: { echo: { route: 'a.b', schema_sha256: '0'.repeat(64) }, add: { route: 'a.b', schema_sha256: '0'.repeat(64) } } }, 'the route a.b is bound twice'] + [{ transport: 'ftp' }, 'transport must be stdio or http'], + [{ transport: 'stdio' }, 'a stdio server needs a command'], + [{ transport: 'http' }, 'an http server needs a url'], + [{ transport: 'stdio', command: 'x', url: 'http://x' }, 'url and headers belong to an http server'], + [{ transport: 'stdio', command: 'x', colour: 'blue' }, 'has unknown keys colour'], + [{ transport: 'stdio', command: 'x', timeout_ms: 10 }, 'timeout_ms must be at least 1000'], + // the allowlist row of the first shape: the tools are bound in the code now, and the file says so + [{ transport: 'stdio', command: 'x', tools: { echo: { route: 'a.b', schema_sha256: '0'.repeat(64) } } }, + 'the tools are bound in the code, not in this file'], + [{ transport: 'stdio', command: 'x', instances: 3 }, 'has unknown keys instances'] ]) { test(`the server file is checked before any connection: ${message}`, () => { servers({ s: entry }); @@ -264,13 +313,7 @@ for (const [entry, message] of [ }); } -test('a route bound by two servers is refused', () => { - const shared = { echo: { route: 'shared.route', schema_sha256: '0'.repeat(64) } }; - servers({ one: { transport: 'stdio', command: 'x', tools: shared }, two: { transport: 'stdio', command: 'y', tools: shared } }); - assert.throws(() => loadServers(), (e) => e.message.includes('bound by both one and two')); -}); - -test('an empty server map starts with no route', () => { +test('an empty server map loads no server', () => { const { log } = servers({}); assert.deepEqual(loadServers(undefined, log), []); assert.ok(log.text().includes('No MCP server configured')); @@ -304,7 +347,7 @@ async function waitFor(port, child, seconds = 20) { throw new Error('the fixture server did not listen in time'); } -test('the http transport serves the same routes', async () => { +test('the http transport serves the same functions', async () => { const port = await freePort(); const child = spawn(process.execPath, [FIXTURE, 'http', String(port)], { stdio: 'ignore' }); try { @@ -312,10 +355,10 @@ test('the http transport serves the same routes', async () => { process.env.FIXTURE_HTTP_TOKEN = 'bearer-value'; const { app, registry } = servers({ remote: { transport: 'http', url: `http://127.0.0.1:${port}/mcp`, - headers: { Authorization: 'Bearer ${FIXTURE_HTTP_TOKEN}' }, - tools: { echo: { route: 'remote.echo', schema_sha256: schemaDigest(offered.echo.input_schema) }, - add: { route: 'remote.add', schema_sha256: schemaDigest(offered.add.input_schema) } } + headers: { Authorization: 'Bearer ${FIXTURE_HTTP_TOKEN}' } } }); + serve(app, registry, 'remote.echo', 'remote', 'echo'); + serve(app, registry, 'remote.add', 'remote', 'add'); await app.boot(); try { assert.equal(ok(await call(registry, 'remote.echo', { text: 'over http' })), 'over http'); @@ -331,7 +374,8 @@ test('the http transport serves the same routes', async () => { }); test('health reports each server and its connection', async () => { - const { app } = servers({ fixture: stdio({ echo: 'fixture.echo' }) }); + const { app, registry } = servers({ fixture: stdio() }); + serve(app, registry, 'fixture.echo', 'fixture', 'echo'); await app.boot(); try { const info = await app.health({ type: 'info' }, {}); @@ -342,7 +386,7 @@ test('health reports each server and its connection', async () => { await app.shutdown(); } assert.deepEqual((await app.health({ type: 'info' }, {})).servers, []); - const lost = new Server({ name: 'gone', transport: 'stdio', tools: [], command: 'x', args: [], env: {}, headers: {}, timeout_ms: 30000, instances: 10 }); + const lost = new Server({ name: 'gone', transport: 'stdio', command: 'x', args: [], env: {}, headers: {}, timeout_ms: 30000 }); app.servers.set('gone', lost); try { await rejects(app.health({ type: 'health' }, {}), 503, 'gone'); @@ -351,15 +395,16 @@ test('health reports each server and its connection', async () => { } }); -test('describe prints the digests and a catalog row', async () => { - const { app, lines } = servers({ fixture: stdio({ echo: 'fixture.echo' }) }); +test('describe prints the digests, the bind lines and a catalog row', async () => { + const { app, registry, lines } = servers({ fixture: stdio() }); + serve(app, registry, 'fixture.echo', 'fixture', 'echo'); const errors = []; assert.equal(await app.describe(['fixture'], (line) => errors.push(line)), 0); const out = lines.join('\n'); assert.ok(out.includes(`schema_sha256: ${schemaDigest(offered.echo.input_schema)}`)); - assert.ok(out.includes('## echo - bound as fixture.echo (digest ok)')); - assert.ok(out.includes('## add - not allowlisted')); - assert.ok(out.includes('"route": "fixture.echo"')); + assert.ok(out.includes('## echo - bound (digest ok)')); + assert.ok(out.includes('## add - not bound')); + assert.ok(out.includes(`bind('fixture', 'add', { schemaSha256: '${schemaDigest(offered.add.input_schema)}' })`)); assert.ok(out.includes('"description": "Echo the text back."')); assert.equal(await app.describe(['unknown'], (line) => errors.push(line)), 1); assert.ok(errors.join('\n').includes('Unknown server(s): unknown')); diff --git a/test/vectors/mcp-binding-vectors.json b/test/vectors/mcp-binding-vectors.json index 64d7ceaf..d160a36e 100644 --- a/test/vectors/mcp-binding-vectors.json +++ b/test/vectors/mcp-binding-vectors.json @@ -1,7 +1,7 @@ { "contract": "mcp-binding", - "version": 1, - "description": "The MCP binding's shared vectors (RFC-0011 / ADR-0033, build plan step 4): the pure half of the binding, run by mercury-python and mercury-nodejs against the same file. digest_cases pin the canonical JSON a tool's input schema is hashed as (keys sorted, no spaces, Unicode kept, SHA-256 hex). verify_cases pin how an allowlist is matched against the tools a server offers (tools/list as plain maps: name, description, input_schema) - the bound routes in allowlist order, or the exact error that stops the boot. result_cases pin how a CallToolResult (content, structured_content, is_error) becomes a route's reply or its error (status and exact message). No server is started by these cases; the transports are tested by each pack with a fixture server.", + "version": 2, + "description": "The MCP binding's shared vectors (RFC-0011 / ADR-0033, build plan step 4; the declaration shape of draft-design-specs/agent-tool-use.md, 2026-11-16): the pure half of the binding, run by mercury-python and mercury-nodejs against the same file. digest_cases pin the canonical JSON a tool's input schema is hashed as (keys sorted, no spaces, Unicode kept, SHA-256 hex). verify_cases pin how the tools the functions of an application bind to a server (bindings: tool, schema_sha256, in declaration order) are matched against the tools the server offers (tools/list as plain maps: name, description, input_schema) - the bound tools in declaration order, or the exact error that stops the boot. result_cases pin how a CallToolResult (content, structured_content, is_error) becomes a function's reply or its error (status and exact message). No server is started by these cases; the transports are tested by each pack with a fixture server.", "digest_cases": [ { "name": "an empty object schema", @@ -65,20 +65,20 @@ ], "verify_cases": [ { - "name": "verify/every-allowlisted-tool-is-offered-and-unchanged", + "name": "verify/every-bound-tool-is-offered-and-unchanged", "server": { - "name": "docs", - "tools": { - "read_text_file": { - "route": "docs.read.text.file", - "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" - }, - "list_directory": { - "route": "docs.list.directory", - "schema_sha256": "923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b" - } - } + "name": "docs" }, + "bindings": [ + { + "tool": "read_text_file", + "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + }, + { + "tool": "list_directory", + "schema_sha256": "923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b" + } + ], "offered": [ { "name": "read_text_file", @@ -115,22 +115,22 @@ ], "expect": { "bound": [ - "docs.read.text.file", - "docs.list.directory" + "read_text_file", + "list_directory" ] } }, { - "name": "verify/a-tool-the-server-offers-but-the-allowlist-omits-is-ignored", + "name": "verify/a-tool-the-server-offers-but-no-function-binds-is-ignored", "server": { - "name": "docs", - "tools": { - "read_text_file": { - "route": "docs.read.text.file", - "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" - } - } + "name": "docs" }, + "bindings": [ + { + "tool": "read_text_file", + "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + } + ], "offered": [ { "name": "read_text_file", @@ -167,21 +167,21 @@ ], "expect": { "bound": [ - "docs.read.text.file" + "read_text_file" ] } }, { "name": "verify/a-missing-tool-names-itself-and-what-is-offered", "server": { - "name": "docs", - "tools": { - "write_file": { - "route": "docs.write.file", - "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" - } - } + "name": "docs" }, + "bindings": [ + { + "tool": "write_file", + "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + } + ], "offered": [ { "name": "read_text_file", @@ -223,14 +223,14 @@ { "name": "verify/a-server-with-no-tools", "server": { - "name": "docs", - "tools": { - "read_text_file": { - "route": "docs.read.text.file", - "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" - } - } + "name": "docs" }, + "bindings": [ + { + "tool": "read_text_file", + "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + } + ], "offered": [], "expect": { "error": "MCP server docs does not offer the tool read_text_file - it offers no tools" @@ -239,14 +239,14 @@ { "name": "verify/a-changed-schema-names-the-tool-and-both-digests", "server": { - "name": "docs", - "tools": { - "read_text_file": { - "route": "docs.read.text.file", - "schema_sha256": "923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b" - } - } + "name": "docs" }, + "bindings": [ + { + "tool": "read_text_file", + "schema_sha256": "923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b" + } + ], "offered": [ { "name": "read_text_file", @@ -282,24 +282,24 @@ } ], "expect": { - "error": "MCP server docs changed the input schema of read_text_file - its digest is now 6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479, the configuration pins 923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b" + "error": "MCP server docs changed the input schema of read_text_file - its digest is now 6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479, the binding pins 923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b" } }, { - "name": "verify/the-first-failure-in-allowlist-order-stops-the-boot", + "name": "verify/the-first-failure-in-declaration-order-stops-the-boot", "server": { - "name": "docs", - "tools": { - "list_directory": { - "route": "docs.list.directory", - "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" - }, - "write_file": { - "route": "docs.write.file", - "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" - } - } + "name": "docs" }, + "bindings": [ + { + "tool": "list_directory", + "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + }, + { + "tool": "write_file", + "schema_sha256": "6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + } + ], "offered": [ { "name": "read_text_file", @@ -335,7 +335,7 @@ } ], "expect": { - "error": "MCP server docs changed the input schema of list_directory - its digest is now 923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b, the configuration pins 6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" + "error": "MCP server docs changed the input schema of list_directory - its digest is now 923b083c9bcab2e3d3e07c7d9b4401688ad9f3d5e2c2f0c48fcd43052bdcb71b, the binding pins 6acc092731905473c2bfced982253c9a85e0190cca13fb933deeaa4069819479" } } ],