Skip to main content
Glama
mcp-tools-surface

mcp-tools-surface

by clarabstract
README.md
# mcp-tools-surface

![AI-DECLARATION: auto](https://img.shields.io/badge/䷼%20AI--DECLARATION-auto-ede9fe?labelColor=ede9fe)

> **Status: vibecoded, not reviewed.** Written by Claude, an AI coding agent,
> in one unattended session from a brief; no human has read the code. It has
> tests through the MCP SDK's own client and raw sockets, against a real
> command runner on PostgreSQL 18, but treat it as unaudited: this is where the
> token check and the scope challenge are enforced for MCP. Details in
> [AI-DECLARATION.md](AI-DECLARATION.md).

The MCP endpoint of a service: each query and mutation of its GraphQL schema
is one MCP tool, served over stateless Streamable HTTP with the official MCP
TypeScript SDK 2 (`@modelcontextprotocol/server` 2.4.0 and
`@modelcontextprotocol/node` 2.1.2, pinned). It serves both protocol eras the
SDK serves: the 2025 `initialize` handshake (through the SDK's stateless
fallback) and the 2026-07-28 per-request revision. A tool call runs the
operation's generated response document through
[graphql-command-runner](../graphql-command-runner)'s `execute`; nothing calls
a resolver. It verifies no tokens itself: the token check comes from
[jwt-tenant-auth](../jwt-tenant-auth), and the input schemas from
[graphql-input-json-schema](../graphql-input-json-schema).

## Mount interface

```ts
import { createMcpSurface } from 'mcp-tools-surface';

const mcp = createMcpSurface({
  runner,                        // from createCommandRunner
  tokenCheck,                    // from createTokenCheck: authenticate and authenticateInTenant
  serviceName: 'shelf',          // scopes shelf:read and shelf:write; also the MCP server's name
  resourceMetadataUrl: 'https://shelf.example.org/.well-known/oauth-protected-resource/mcp',
  maxRequestBodySize: 1024 * 1024, // the default
  logger,                        // { error, warn }; console by default; one that throws is ignored
});

// In the host's router:
if (path === mcp.path) return mcp.handle(req, res);   // mcp.path is '/mcp'
// handle serves any request it is given, so route only that exact path to it.
// And on the server, so that Node doesn't answer `Expect: 100-continue` itself:
server.on('checkContinue', route);
```

```ts
function createMcpSurface(options: McpSurfaceOptions): McpSurface;

interface McpSurfaceOptions {
  runner: Pick<CommandRunner, 'schema' | 'operations' | 'execute'>;
  tokenCheck: Pick<TokenCheck, 'authenticate' | 'authenticateInTenant'>;
  serviceName: string;
  resourceMetadataUrl: string;
  maxRequestBodySize?: number;
  logger?: Logger;
}

interface McpSurface {
  readonly path: '/mcp';
  handle(req: IncomingMessage, res: ServerResponse): void | Promise<void>;
}
```

The host serves the login discovery document (the protected-resource
metadata); `resourceMetadataUrl` is its absolute address, at the public origin
the settings give, and every challenge points at it. `createMcpSurface` throws
a `TypeError` naming every problem with the options, including an operation
whose arguments can't be described (a custom scalar it doesn't know, a
recursive input type).

Exports: `createMcpSurface`, `MCP_PATH` (`'/mcp'`), `SCALAR_WIRE_FORMS`,
`TENANT_ARGUMENT` (`'tenant'`), and the types
`McpSurfaceOptions`, `McpSurface`, `Runner`.

## Tools

- **One tool per operation**, named after it, described by its description
  in the schema. The server's instructions are the schema's own description.
- **Input schema:** exactly the operation's arguments, as JSON Schema with
  every input type written out in full (no `$ref`), from
  graphql-input-json-schema. The framework scalars are strings: `Date` with
  `format: date`, `DateTime` with `format: date-time`, `Decimal` and `Cursor`
  plain. A mutation the schema doesn't declare idempotent also has the
  optional `idempotencyKey` the runner adds to it. The SDK checks a call's
  arguments against this schema (unknown arguments included) and refuses a
  mismatch as a tool error; the runner checks every value again.
- **Hints:** `readOnlyHint` for a query; `destructiveHint` for a mutation
  with `@effect(kind: DESTRUCTIVE)`; `idempotentHint` for a query and for a
  mutation with `@effect(idempotent: true)`.
- **Result:** one text block holding the generated response as JSON: the
  fields the runner's one rule picks, with each link (an entity inside
  another entity) as the linked entity's bare ID, and a list of links as a
  list of IDs (the runner's `withLinksAsIds`).

| Outcome | Tool result |
| --- | --- |
| Ran | the generated response as JSON; `null` for a null result that isn't an entity |
| A declared error in the payload | `isError: true`, the whole generated response as JSON, so the error's `__typename`, `message` and fields are there |
| A query for one record (a nullable entity) that found none | `isError: true`, `{"__typename":"NotFound","message":"Nothing was found in this tenant."}` |
| Bad input, a role not allowed, an unexpected failure (from the runner) | `isError: true`, the runner's message (`Unexpected error.` for a failure, whose cause is logged) |
| Arguments that don't fit the input schema | `isError: true`, the SDK's validation message |
| A tenant problem (below) | `isError: true`, its message |

## The tenant argument

For a caller whose token lists more than one tenant, every tool also takes an
optional `tenant` argument: a string whose description and `examples` list
the token's tenants. It is not an enum: like the `Tenant-Id` header it takes a
tenant ID in any case, and the token check refuses one the token doesn't list.
A caller in one tenant gets no such argument, and a call that sends one is
refused like any unknown argument.

- Named: the call runs in that tenant, through jwt-tenant-auth's
  `authenticateInTenant` (the same token check). If the request's `Tenant-Id`
  header names another tenant, the call is refused as bad input; the same
  tenant in both is fine.
- Not named: the call runs in the tenant the token check chose for the
  request: the `Tenant-Id` header's, else the token's default, else its only
  tenant. A token that lists several tenants and marks none, on a request
  with no header, still lists the tools; a call that names no tenant is then
  refused as bad input.

## Challenges and refusals before the body

Everything in this table is answered from the request's headers, before the
SDK sees the request or any of the body is read, with `Connection: close`;
the connection is destroyed once the answer is written.

| Request | Answer |
| --- | --- |
| No `Authorization` header | 401, `WWW-Authenticate: Bearer resource_metadata="<url>", scope="<svc>:read <svc>:write"`, body `{"error":"invalid_token","error_description":…}` |
| A token that isn't valid (forged, expired, another audience or issuer, no user) | 401, `WWW-Authenticate: Bearer error="invalid_token", error_description="…", resource_metadata="<url>", scope="…"`, same body |
| A token listing no tenant, or a default it doesn't list, or a `Tenant-Id` it doesn't list | 403, JSON-RPC error body (`id: null`, code `-32003`) |
| A malformed `Tenant-Id` | 400, JSON-RPC error body (code `-32602`) |
| The token check throws (issuer keys unreachable) | 500, `Unexpected error.`; logged by jwt-tenant-auth's `logAuthenticateFailure` |
| A stated `Content-Length` over the limit | 413, JSON-RPC error body |

**The scope challenge.** A query needs `<svc>:read` and a mutation
`<svc>:write`, granted by exactly that name. A tool call without it gets, before
the call runs:

```
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", error_description="This tool needs the shelf:write scope.", scope="shelf:write", resource_metadata="<url>"
```

This is the SDK's per-tool `scopeChallenge`; the surface resolves the
caller for the call first (tenant argument included), so the challenge is
built from the token's own scopes. A call that can't run anyway (no tenant
chosen, a tenant the token doesn't list) gets its tool error instead.
Listing tools needs no particular scope.

The forms follow the MCP authorization specification, revision 2026-07-28:
<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization>
(sections "Scope Selection Strategy", "Error Handling" and "Scope Challenge
Handling"), with RFC 6750 section 3
(<https://datatracker.ietf.org/doc/html/rfc6750#section-3>) and RFC 9728
(<https://datatracker.ietf.org/doc/html/rfc9728>).

## Limits

- **Body:** 1 MiB by default (`maxRequestBodySize`). A stated length over it
  is refused from the headers, before any `100 Continue`. A body with no
  stated length is cut off by the SDK's Node adapter (its
  `maxRequestBodySize`), which answers 413; the surface closes the connection
  after that answer. A client still sending may see a reset instead of the
  413. A caller that goes away mid-body is not logged.
- **Batches:** one JSON-RPC message per request. A JSON array body is refused
  with 400 (code `-32602`) before any of it runs, in either era.
- **`Expect: 100-continue`:** the surface sends `100 Continue` itself, and
  only once the token check and the stated length have passed. This needs the
  server's `checkContinue` event routed to `handle`.
- **Pipelining:** requests on one connection are handled in turn with
  node-http-refusal's `admitRequest` (which also puts the token check before
  any `100 Continue`), so nothing pipelined behind a refusal runs.
- **How long a body may take** is the host's `requestTimeout`.

## Stateless

A fresh `McpServer` is built for each HTTP request, and nothing is kept
between requests: no session IDs, `GET` for a server stream is answered 405,
and `subscriptions/listen` (2026-07-28) is refused at once with the SDK's
`Subscription limit reached` (the subscription cap is 0). Tools never send
notifications, so every answer is a single JSON body or an SSE stream that
ends with the request.

## Tests

```
npm install
npm test        # checks the sibling copies, builds, type-checks, runs every test
```

The tests start one embedded PostgreSQL 18 cluster per run (copied from
graphql-command-runner's `test/support/cluster.ts`), give each file its own
database with a small shelf service (`test/fixtures/shelf`), and run
jwt-tenant-auth's real token check against its local issuer. Tool calls go
through `@modelcontextprotocol/client` 2.4.0, in both eras; refusals and the
body limit are also checked over raw sockets. They need Node 24 or later for
`--test-global-setup`.

The siblings are installed as copies (`install-links=true`), so every
package shares one copy of `graphql`. After rebuilding a sibling, run
`npm run refresh-siblings`; `npm test` refuses to run against stale copies.