@graxia/mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -2
  3. package/dist/auth/bearer.d.ts +17 -0
  4. package/dist/auth/bearer.d.ts.map +1 -0
  5. package/dist/auth/metadata.d.ts +8 -0
  6. package/dist/auth/metadata.d.ts.map +1 -0
  7. package/dist/auth/principal.d.ts +17 -0
  8. package/dist/auth/principal.d.ts.map +1 -0
  9. package/dist/auth/resolve.d.ts +4 -0
  10. package/dist/auth/resolve.d.ts.map +1 -0
  11. package/dist/auth/scopes.d.ts +14 -0
  12. package/dist/auth/scopes.d.ts.map +1 -0
  13. package/dist/auth/types.d.ts +70 -0
  14. package/dist/auth/types.d.ts.map +1 -0
  15. package/dist/body.d.ts +6 -0
  16. package/dist/body.d.ts.map +1 -0
  17. package/dist/calls.d.ts +14 -0
  18. package/dist/calls.d.ts.map +1 -0
  19. package/dist/codes.d.ts +21 -0
  20. package/dist/codes.d.ts.map +1 -0
  21. package/dist/context.d.ts +20 -0
  22. package/dist/context.d.ts.map +1 -0
  23. package/dist/cors.d.ts +7 -0
  24. package/dist/cors.d.ts.map +1 -0
  25. package/dist/create.d.ts +29 -0
  26. package/dist/create.d.ts.map +1 -0
  27. package/dist/index.d.ts +8 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +1533 -0
  30. package/dist/index.js.map +45 -0
  31. package/dist/operations/build.d.ts +10 -0
  32. package/dist/operations/build.d.ts.map +1 -0
  33. package/dist/operations/constraint.d.ts +16 -0
  34. package/dist/operations/constraint.d.ts.map +1 -0
  35. package/dist/operations/documents.d.ts +13 -0
  36. package/dist/operations/documents.d.ts.map +1 -0
  37. package/dist/operations/input-schema.d.ts +12 -0
  38. package/dist/operations/input-schema.d.ts.map +1 -0
  39. package/dist/operations/input-type.d.ts +18 -0
  40. package/dist/operations/input-type.d.ts.map +1 -0
  41. package/dist/operations/naming.d.ts +5 -0
  42. package/dist/operations/naming.d.ts.map +1 -0
  43. package/dist/operations/output-schema.d.ts +11 -0
  44. package/dist/operations/output-schema.d.ts.map +1 -0
  45. package/dist/operations/problems.d.ts +27 -0
  46. package/dist/operations/problems.d.ts.map +1 -0
  47. package/dist/operations/register.d.ts +20 -0
  48. package/dist/operations/register.d.ts.map +1 -0
  49. package/dist/operations/types.d.ts +49 -0
  50. package/dist/operations/types.d.ts.map +1 -0
  51. package/dist/operations/variable-usage.d.ts +16 -0
  52. package/dist/operations/variable-usage.d.ts.map +1 -0
  53. package/dist/operations/visible.d.ts +10 -0
  54. package/dist/operations/visible.d.ts.map +1 -0
  55. package/dist/options.d.ts +116 -0
  56. package/dist/options.d.ts.map +1 -0
  57. package/dist/origin-options.d.ts +9 -0
  58. package/dist/origin-options.d.ts.map +1 -0
  59. package/dist/origin.d.ts +18 -0
  60. package/dist/origin.d.ts.map +1 -0
  61. package/dist/pipeline.d.ts +16 -0
  62. package/dist/pipeline.d.ts.map +1 -0
  63. package/dist/refusal.d.ts +4 -0
  64. package/dist/refusal.d.ts.map +1 -0
  65. package/dist/server.d.ts +28 -0
  66. package/dist/server.d.ts.map +1 -0
  67. package/dist/tools/execute.d.ts +32 -0
  68. package/dist/tools/execute.d.ts.map +1 -0
  69. package/dist/tools/guard.d.ts +8 -0
  70. package/dist/tools/guard.d.ts.map +1 -0
  71. package/dist/tools/index.d.ts +17 -0
  72. package/dist/tools/index.d.ts.map +1 -0
  73. package/dist/tools/operation.d.ts +35 -0
  74. package/dist/tools/operation.d.ts.map +1 -0
  75. package/dist/tools/result.d.ts +13 -0
  76. package/dist/tools/result.d.ts.map +1 -0
  77. package/dist/tools/schema.d.ts +319 -0
  78. package/dist/tools/schema.d.ts.map +1 -0
  79. package/dist/tools/strict.d.ts +12 -0
  80. package/dist/tools/strict.d.ts.map +1 -0
  81. package/dist/toolset.d.ts +30 -0
  82. package/dist/toolset.d.ts.map +1 -0
  83. package/dist/view-cache.d.ts +13 -0
  84. package/dist/view-cache.d.ts.map +1 -0
  85. package/dist/view.d.ts +16 -0
  86. package/dist/view.d.ts.map +1 -0
  87. package/docs/README.md +9 -0
  88. package/docs/guide/auth.md +247 -0
  89. package/docs/guide/getting-started.md +82 -0
  90. package/docs/guide/operations.md +221 -0
  91. package/docs/guide/security.md +122 -0
  92. package/docs/guide/tools.md +102 -0
  93. package/docs/roadmap.md +32 -0
  94. package/docs/troubleshooting-auth.md +101 -0
  95. package/docs/troubleshooting.md +205 -0
  96. package/package.json +71 -5
@@ -0,0 +1,82 @@
1
+ # Getting started
2
+
3
+ ## Install and mount
4
+
5
+ ```sh
6
+ bun add @graxia/mcp @graxia/core graphql
7
+ ```
8
+
9
+ ```ts
10
+ import { createGraxia } from '@graxia/core';
11
+ import { createMcp } from '@graxia/mcp';
12
+
13
+ // `schema` is the one from the core quick start
14
+ const graxia = createGraxia({ schema });
15
+ const mcp = createMcp(graxia, { name: 'library' });
16
+
17
+ Bun.serve({
18
+ routes: { '/mcp': (request, server) => mcp.fetch(request, { server }) },
19
+ fetch: graxia.fetch,
20
+ });
21
+ ```
22
+
23
+ `createMcp(graxia, options)` reads the schema and the body limit from the instance
24
+ (`graxia.schema`, `graxia.limits.bodyBytes`, `@graxia/core` 0.5), so nothing is given twice. `mcp.fetch(request, serverContext?)` is a Web `Request` in, a
25
+ `Response` out, and never rejects. `mcp.dispose()` stops the handler (in-flight requests are aborted),
26
+ like `graxia.dispose()`.
27
+
28
+ **In production.** graxia runs trusted documents in `strict` mode there (`NODE_ENV=production`), so
29
+ agents cannot run a document they write: pass `operations: { documents }` to give them your
30
+ persisted operations as tools ([typed tools](./operations.md)), or `createMcp` reports it through
31
+ `onError` at boot. A hand-made host (a test double) must pass `trustedDocuments:
32
+ graxia.trustedDocuments` along with `execute`, `schema` and `limits`.
33
+
34
+ ## Transport
35
+
36
+ Streamable HTTP, stateless: every `POST` carries one JSON-RPC message or a batch of them and is answered on its own.
37
+ There is no `Mcp-Session-Id`. `GET` (the optional server-to-client stream) and `DELETE` (closing a
38
+ session) answer 405 with a `fix`, as the spec allows. Only `application/json` bodies are accepted.
39
+
40
+ ## Connect a client
41
+
42
+ Claude Code:
43
+
44
+ ```sh
45
+ claude mcp add --transport http library http://localhost:3000/mcp
46
+ ```
47
+
48
+ With `auth` set, give the client its token (`--header "Authorization: Bearer <token>"`) or let its
49
+ OAuth support follow the 401 to the metadata ([auth](./auth.md)). Any other client takes the URL as a Streamable HTTP server. In a test, use
50
+ `@modelcontextprotocol/client` (`Client` and `StreamableHTTPClientTransport`) against `Bun.serve({ port: 0 })`.
51
+
52
+ ## Host context
53
+
54
+ `serverContext` is the second argument of `mcp.fetch`, typed like `graxia.fetch`'s (it is required
55
+ when your host context has required keys, see core's [context guide](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/context.md)). Graxia
56
+ merges it into the context of every operation, and `can` receives it:
57
+
58
+ ```ts
59
+ Bun.serve({
60
+ routes: {
61
+ '/mcp': (request, server) =>
62
+ mcp.fetch(request, { server, tenant: tenantOf(request) }),
63
+ },
64
+ fetch: (request, server) =>
65
+ graxia.fetch(request, { server, tenant: tenantOf(request) }),
66
+ });
67
+ ```
68
+
69
+ The request's own headers (an `Authorization`, a cookie) are forwarded to `graxia.execute` too, minus
70
+ `Content-Type`, `Content-Length`, `Accept`, `Host`, `Origin` and the `Mcp-*` headers (the
71
+ serverContext never travels in a header: a client cannot forge it), so a `context`
72
+ that reads them works the same over MCP and HTTP.
73
+
74
+ ## Typed tools
75
+
76
+ To give agents your persisted operations as tools with typed arguments, see
77
+ [persisted operations as typed tools](./operations.md).
78
+
79
+ ## Server instructions
80
+
81
+ `instructions` is shown to the model when it connects: say what the API is for in two or three
82
+ sentences. The tools already tell it to call `graphql_schema` first.
@@ -0,0 +1,221 @@
1
+ # Persisted operations as typed tools
2
+
3
+ Give `createMcp` the operations your clients already persist and each one becomes an MCP tool: a
4
+ name, a description, a JSON Schema for its arguments (from the operation's variables) and one for
5
+ its result (from its selection set). An agent calls `book_by_id({ id: "1" })` instead of writing
6
+ GraphQL, and runs only operations you have reviewed.
7
+
8
+ ```ts
9
+ import { createGraxia } from '@graxia/core';
10
+ import { createMcp } from '@graxia/mcp';
11
+ import manifest from './persisted-documents.json';
12
+
13
+ const graxia = createGraxia({ schema, trustedDocuments: { manifest } });
14
+ const mcp = createMcp(graxia, {
15
+ name: 'library',
16
+ operations: { documents: manifest },
17
+ });
18
+ ```
19
+
20
+ That is all: no handler to write. With this operation in the manifest
21
+
22
+ ```graphql
23
+ """
24
+ Find a book by its id.
25
+ """
26
+ query BookById(
27
+ """
28
+ The book id.
29
+ """
30
+ $id: ID!
31
+ ) {
32
+ book(id: $id) {
33
+ id
34
+ title
35
+ }
36
+ }
37
+ ```
38
+
39
+ `tools/list` holds
40
+
41
+ ```json
42
+ {
43
+ "name": "book_by_id",
44
+ "title": "BookById",
45
+ "description": "Find a book by its id.",
46
+ "inputSchema": {
47
+ "type": "object",
48
+ "properties": { "id": { "type": "string", "description": "The book id." } },
49
+ "required": ["id"],
50
+ "additionalProperties": false
51
+ },
52
+ "annotations": { "readOnlyHint": true }
53
+ }
54
+ ```
55
+
56
+ plus an `outputSchema`, and `tools/call` with `{ "id": "1" }` answers
57
+ `{ "data": { "book": { "id": "1", "title": "Dune" } } }`.
58
+
59
+ ## The manifest
60
+
61
+ `operations.documents` is core's `TrustedManifest`, in the three formats `trustedDocuments.manifest`
62
+ takes: an object of id to source (GraphQL Code Generator's `persisted-documents.json`, Relay's
63
+ persisted queries file), an Apollo persisted query manifest
64
+ (`{ format: 'apollo-persisted-query-manifest', version: 1, operations: [{ id, body }] }`), or a
65
+ `Map`. It is usually the same object you give `trustedDocuments`, but it does not have to be.
66
+ Your client toolchain writes it: core's
67
+ [trusted documents guide](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/trusted-documents.md)
68
+ shows how for each one. A real client manifest holds every operation of the application, so the
69
+ first boot lists the ones without a description: narrow it with `include`, or fill `descriptions`.
70
+
71
+ - One tool per **named** operation. The tool name is the operation name in snake case
72
+ (`BookById` → `book_by_id`, `HTTPStatus` → `http_status`); the title is the operation name.
73
+ - **Queries** are tools. **Mutations** are tools only with `mutations: true`.
74
+ **Subscriptions** are skipped: MCP tools answer once.
75
+ - `include` picks the operations to offer. An operation it leaves out is not validated and needs no
76
+ description; every document must still parse and name its operations:
77
+
78
+ ```ts
79
+ operations: {
80
+ documents: manifest,
81
+ include: ({ name, kind, id }) => kind === 'query' && !name.startsWith('Admin'),
82
+ },
83
+ ```
84
+
85
+ Everything is checked once, in `createMcp`, against the full schema. It throws one
86
+ `GraxiaConfigError` listing **every** problem with its fix, so a manifest is corrected in one pass
87
+ (see [troubleshooting](../troubleshooting.md)): an anonymous operation, two operations giving one
88
+ tool name, a name starting with `graphql_` or longer than 128 characters, a document that does not
89
+ parse or validate, `@defer` or `@stream`, introspection, a missing description, and a
90
+ `descriptions` key that names no operation.
91
+
92
+ ## Descriptions
93
+
94
+ A description is **required**: an agent picks a tool by it. Write it where the operation lives,
95
+ with the executable-descriptions syntax graphql 17 parses, or give it by operation name:
96
+
97
+ ```ts
98
+ operations: {
99
+ documents: manifest,
100
+ descriptions: { BookById: 'Find a book by its id.' }, // wins over the document's own
101
+ },
102
+ ```
103
+
104
+ A variable's description becomes the `description` of its property. A variable without one takes
105
+ the description of the argument or input field it feeds.
106
+
107
+ > Your toolchain must keep the descriptions in the manifest. GraphQL Code Generator's client preset
108
+ > keeps them when the project's `graphql` is 16.12 or later (flattened to one line); before 16.12
109
+ > the sources do not parse with a description, so use `descriptions`. Open
110
+ > `persisted-documents.json` to check: the boot error names each operation that lacks one.
111
+
112
+ ## The input schema
113
+
114
+ JSON Schema 2020-12, `type: "object"`, `additionalProperties: false`, one property per variable.
115
+
116
+ | GraphQL | JSON Schema |
117
+ | ------------------------------ | -------------------------------------------------------------------------------- |
118
+ | `Int` | `{ "type": "integer" }` |
119
+ | `Float` | `{ "type": "number" }` |
120
+ | `String`, `ID` | `{ "type": "string" }` |
121
+ | `Boolean` | `{ "type": "boolean" }` |
122
+ | an enum | `{ "type": "string", "enum": [...] }`, described values listed in `description` |
123
+ | a list | `{ "type": "array", "items": ... }` |
124
+ | an input object | `{ "$ref": "#/$defs/Name" }`, the object under `$defs` (so recursive types work) |
125
+ | a `@oneOf` input object | `oneOf`, one branch per field |
126
+ | a custom scalar | `{}` with the scalar's description (any JSON value; no `format` is guessed) |
127
+ | nullable (`String`) | `"type": ["string", "null"]`; for an input object `anyOf` with `null` |
128
+ | non-null without a default | listed in `required` |
129
+ | a default (`$first: Int = 10`) | `"default": 10` |
130
+ | a deprecated input field | `"deprecated": true` |
131
+
132
+ ### `@constraint`
133
+
134
+ `@constraint` (from `@graxia/core/agent`) becomes `minLength`, `maxLength`, `minimum`, `maximum`,
135
+ `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `pattern`, `format`, and on a list `minItems`
136
+ and `maxItems` (the other limits then apply to the items). It is read:
137
+
138
+ - on **input fields**, inside `$defs`;
139
+ - for a **variable**, on the arguments and input fields the variable is used at. A variable used at
140
+ several places gets the tightest bound of each kind; `pattern`, `format` and `multipleOf` are
141
+ kept when the usages agree and left out when they differ.
142
+
143
+ The schema guides the agent; it is not the check. An argument the schema does not have is refused
144
+ (`MCP_UNKNOWN_ARGUMENT`, with the accepted names). The others go to graxia as variables, unchanged,
145
+ and graxia's own coercion and your resolvers decide: a wrong argument answers with a GraphQL error
146
+ (`Variable "$id" has invalid value: …`, code `BAD_USER_INPUT`) whose fix is
147
+ `Correct the arguments: see the tool's input schema.`
148
+
149
+ ## The output schema
150
+
151
+ ```json
152
+ {
153
+ "type": "object",
154
+ "properties": {
155
+ "data": {
156
+ "type": ["object", "null"],
157
+ "properties": { "book": { "...": "..." } }
158
+ },
159
+ "errors": {
160
+ "type": "array",
161
+ "items": { "...": "message, path, extensions.code, extensions.fix" }
162
+ }
163
+ }
164
+ }
165
+ ```
166
+
167
+ `data` follows the selection set, by response key (aliases included): a nullable field also accepts
168
+ `null`, lists are arrays, `__typename` is a string, named and inline fragments are merged.
169
+ On an interface or a union the fields of every fragment are merged into one object, and a field
170
+ selected only for some of the possible types (or under `@skip` / `@include`) is not required:
171
+ there is no branch per type. When several selections share one response key
172
+ (`... on Book { author { name } } ... on Mag { author { age } }`), a nested key is required only
173
+ if every one of them selects it, or one that always applies does. The same key with different
174
+ types in two fragments is an `anyOf`.
175
+ A custom scalar is `{}`.
176
+
177
+ The result keeps the shape of the generic tools ([results](./tools.md#results)):
178
+ `structuredContent` is `{ data?, errors? }`, `isError` is `true` when there is no `data`.
179
+
180
+ ## Strict trusted documents
181
+
182
+ With `trustedDocuments` in `strict` mode (the default under `NODE_ENV=production`) the typed tools
183
+ are the only tools that run operations: `graphql_query` and `graphql_mutate` are not listed, and a
184
+ call answers `PERSISTED_QUERY_ONLY` with a fix naming the typed tools
185
+ ([tools](./tools.md#trusted-documents)). The typed tools run through `graxia.execute`, in process,
186
+ which graxia trusts as it trusts your own server code: the operations are yours, read at boot; the
187
+ agent only chooses one and gives its variables. Limits, cost, masking, field rate limits and your
188
+ `context` still apply. A strict server without `operations` boots, with `graphql_schema` alone.
189
+
190
+ ## Only the typed tools
191
+
192
+ ```ts
193
+ createMcp(graxia, {
194
+ name: 'library',
195
+ operations: { documents: manifest },
196
+ genericTools: false, // no graphql_query, no graphql_mutate
197
+ });
198
+ ```
199
+
200
+ `graphql_schema` stays, and names the typed tools. `genericTools: false` without `operations`, or
201
+ with operations that give no tool, throws: there would be nothing to call. This is the tightest
202
+ surface: see [security](./security.md#typed-tools-only).
203
+
204
+ ## Permissions and scopes
205
+
206
+ - **`can`**: a tool is listed for a caller only when its operation is valid against the schema that
207
+ caller may see. A tool using a field behind a `@needs` they lack is not listed, and calling it
208
+ answers `Tool <name> not found`, exactly like a tool that does not exist.
209
+ - **`auth`**: query tools need the read scope (`mcp:read`), mutation tools the write scope
210
+ (`mcp:write`). A read-only token does not see the mutation tools, and calling one is the same 403
211
+ step-up as `graphql_mutate` ([auth](./auth.md#scopes-and-step-up)), unless `can` hides the tool
212
+ from that caller: then it is `Tool <name> not found`.
213
+ - Query tools carry `readOnlyHint: true`; mutation tools `readOnlyHint: false, destructiveHint: true`.
214
+
215
+ ## Cost
216
+
217
+ Parsing, validation and both schemas are computed once, in `createMcp`. Per request only the
218
+ filter by the caller's view runs: once for all callers without `can`; with `can`, once per
219
+ `tools/list` and `tools/call` request (the view is built, so `can` runs, for those two only:
220
+ `initialize`, `ping` and notifications never call it). When `can` throws, nothing typed is listed
221
+ and a call answers `The server failed to run the operation. Fix: retry later.`
@@ -0,0 +1,122 @@
1
+ # Security
2
+
3
+ ## Authentication
4
+
5
+ Set `auth` and `@graxia/mcp` is an OAuth resource server: bearer tokens, scopes, protected
6
+ resource metadata ([the auth guide](./auth.md)). Every request then needs a token your
7
+ `verifyToken` accepts, issued for this resource (the audience is checked by default), and
8
+ `graphql_mutate` and the typed tools of mutations need the write scope (a 403 naming the tool
9
+ called; with `mutations` off they are `Tool … not found`).
10
+
11
+ Without `auth` nothing authenticates: mount the endpoint behind your own auth (a reverse proxy, a
12
+ check in the `Bun.serve` route before `mcp.fetch`) and treat it as you would `/graphql`. Keep
13
+ `graphql_mutate` off (`mutations` defaults to `false`) unless the caller is trusted.
14
+
15
+ ```ts
16
+ routes: {
17
+ '/mcp': async (request, server) => {
18
+ const principal = await authenticate(request);
19
+ if (!principal) return new Response('Unauthorized', { status: 401 });
20
+ return mcp.fetch(request, { server, principal });
21
+ },
22
+ },
23
+ ```
24
+
25
+ ## `can`
26
+
27
+ `can(request, serverContext, auth)` (`auth` is the verified token, with `auth` set) returns a function `permission => boolean` (it may be async). The
28
+ tools describe and validate against the schema as that caller sees it, so a field behind `@needs`
29
+ they lack is "Cannot query field": the agent can neither see it nor ask for it. The `@needs` is
30
+ also whatever your own resolvers or plugins enforce at run time: `can` is the view, not the lock.
31
+
32
+ `can` shapes what the agent sees and may ask for, not the objects a field returns. A union or
33
+ interface field the caller sees can still return objects of a type the view hides: the agent cannot
34
+ name that type in a fragment, but `__typename` and the interface's fields come back. A resolver of
35
+ a union or interface field must itself leave out the objects the caller may not read.
36
+
37
+ ## Typed tools only
38
+
39
+ `graphql_query` lets an agent write any operation the caller may see. To let it run only
40
+ operations you have reviewed, give them as [typed tools](./operations.md) and turn the generic
41
+ ones off:
42
+
43
+ ```ts
44
+ createMcp(graxia, {
45
+ name: 'library',
46
+ operations: { documents: manifest },
47
+ genericTools: false,
48
+ });
49
+ ```
50
+
51
+ The agent then chooses a tool and gives its variables; it never sends a document. A typed tool is
52
+ listed only when its operation is valid in the caller's view, and a mutation tool needs
53
+ `mutations: true` and, with `auth`, the write scope. `operations.documents` is trusted like your
54
+ own code: build it from your repository, never from a request.
55
+
56
+ ## Strict trusted documents
57
+
58
+ `graxia.execute` runs in process and skips the trusted-documents check (it is your own code
59
+ calling). `@graxia/mcp` forwards documents written by an agent, so it applies the mode itself:
60
+ when `graxia.trustedDocuments.mode` is `strict` (the default under `NODE_ENV=production`),
61
+ `graphql_query` and `graphql_mutate` are not listed and a call answers `PERSISTED_QUERY_ONLY`
62
+ without running anything. Only the typed tools run, each a document you gave at boot. In `mixed`
63
+ mode the generic tools run any document the caller's view allows, as `/graphql` does.
64
+
65
+ ## Origin, Host and DNS rebinding
66
+
67
+ A browser can be tricked into calling a local MCP server by a hostile page whose domain is
68
+ re-pointed at `127.0.0.1` (DNS rebinding): the page then talks to your server as its own origin.
69
+ Two checks stop it, both only for a request that carries an `Origin` header:
70
+
71
+ - the `Origin` must be in `allowedOrigins`, **or**
72
+ - it must be the endpoint's own origin **and** the `Host` header must name a hostname of
73
+ `allowedHosts` (default `localhost`, `127.0.0.1`, `[::1]`). A rebound `evil.example` is its own
74
+ origin, but it is not an allowed host: 403.
75
+
76
+ A request without `Origin` (a CLI, a server, an IDE) passes: it is not a browser. For a
77
+ non-local endpoint set the public hostname, without port:
78
+
79
+ ```ts
80
+ createMcp(graxia, { name: 'library', allowedHosts: ['mcp.example.com'] });
81
+ ```
82
+
83
+ Behind a proxy that terminates TLS the request reaches Bun as `http://`, so the endpoint's own
84
+ origin is `http://…`, not the public one: list the public origin in `allowedOrigins`
85
+ (`https://mcp.example.com`) and the hostname in `allowedHosts`. Entries must be exact (a hostname
86
+ without port; an origin as `scheme://host[:port]`): `createMcp` throws on one that can never match.
87
+
88
+ ## CORS
89
+
90
+ A browser client on another origin needs `allowedOrigins: ['https://app.example']`. Its `OPTIONS`
91
+ preflight is then answered 204 (`Access-Control-Allow-Origin`, `-Methods: POST`, `-Headers`
92
+ including `content-type`, `authorization`, `mcp-protocol-version` and `mcp-session-id`,
93
+ `Vary: Origin`) and every response to it carries `Access-Control-Allow-Origin` and exposes
94
+ `WWW-Authenticate`. Preflights never need a token. A preflight from
95
+ any other origin is a 403 and gets no CORS header.
96
+
97
+ ## Body size and type
98
+
99
+ A POST body over the instance's `limits.bodyBytes` (1 MiB by default, read from `graxia.limits`) is
100
+ a 413. Only `application/json` is accepted (415 otherwise).
101
+
102
+ ## Failures are reported, not shown
103
+
104
+ An unexpected failure (a throwing `can`, a failing transport) is sent to `onError` (default
105
+ `console.error`) with its cause; the agent only sees a generic message. The default sink skips the
106
+ SDK's protocol rejections (messages starting with `Rejected `, a client's own mistake); pass your
107
+ own `onError` to see them, or `false` to silence everything.
108
+
109
+ A document that does not parse is refused by the MCP server itself (`GRAPHQL_PARSE_FAILED`) and never
110
+ reaches `graxia.execute`, so a lenient parser set by a plugin cannot run what the visibility checks
111
+ have not seen. The checks see the document graphql's own parser reads: a plugin parser
112
+ (`setParseFn`) that rewrites a valid document into another one is trusted like any plugin, since it
113
+ already decides what runs on `/graphql` too.
114
+
115
+ CORS preflights echo the headers the browser asks for (`Access-Control-Request-Headers`), so custom
116
+ auth headers work from an allowed origin.
117
+
118
+ ## What graxia still enforces
119
+
120
+ Every operation goes through `graxia.execute`: depth and alias limits, cost, masking of resolver
121
+ errors, field rate limits, and your `context`. MCP does not bypass any of them, and it refuses
122
+ agent-written documents itself in `strict` trusted-documents mode (above).
@@ -0,0 +1,102 @@
1
+ # Tools
2
+
3
+ Every tool sees the schema as the caller may see it: with `can`, a field behind `@needs` the caller
4
+ lacks does not exist for them (it is neither described nor accepted).
5
+
6
+ With `operations`, each persisted operation is one more tool, with typed arguments: see
7
+ [persisted operations as typed tools](./operations.md). `genericTools: false` removes
8
+ `graphql_query` and `graphql_mutate` and keeps `graphql_schema` and the typed tools.
9
+
10
+ ## `graphql_schema`
11
+
12
+ Input `{ search?: string, types?: string[] }`.
13
+
14
+ - **No input**: the operations the caller can use (root fields with their arguments and the first
15
+ line of their description, `Query`, and `Mutation` only when `mutations` is on) and the list of
16
+ type names (the `Mutation` root is not offered, nor found by `search`, unless `mutations` is on).
17
+ With `operations` it ends with the typed tools this caller has, and says to prefer them (with
18
+ `genericTools: false`, or in strict trusted-documents mode, that they are the only way to run
19
+ operations).
20
+ - **`types`**: the SDL of those types, with descriptions, `@deprecated` and the applied `@needs`,
21
+ `@constraint` and `@errors`, plus the definition of each of those directives used. A name that
22
+ does not exist is listed as unknown, with a fix.
23
+ - **`search`**: every word (case-insensitive) must appear in the type's name or description, or in
24
+ a field or enum value name or description. The answer is the SDL of the matching types, at most
25
+ 50 (`types` takes at most 50 names too); when more match it says so and tells the agent to narrow the search.
26
+
27
+ ## `graphql_query`
28
+
29
+ Input `{ query: string, variables?: object, operationName?: string }`. The document is parsed and
30
+ validated against the caller's view, then run through `graxia.execute`, so operation limits, cost,
31
+ masking and field rate limits apply as they do on HTTP ([trusted documents](#trusted-documents) below).
32
+
33
+ Introspection (`__schema`, `__type`) is refused: it would show fields `@needs` hides. Use
34
+ `graphql_schema`. `__typename` stays allowed. Only the validation rules that decide what the caller
35
+ may see run on the view (unknown fields, types and arguments, impossible fragment spreads);
36
+ limits, cost and the rest of validation are graxia's, when the operation runs, with graxia's own
37
+ codes. A document that does not parse is refused here (the token limit of graxia applies) and never handed to graxia.
38
+
39
+ ### Refusals
40
+
41
+ | input | `extensions.code` | message | fix |
42
+ | --------------------------------------------- | ---------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------- |
43
+ | a document that does not parse | `GRAPHQL_PARSE_FAILED` | the parser's message | correct the syntax |
44
+ | an unknown or hidden field, type or argument | `GRAPHQL_VALIDATION_FAILED` | `Cannot query field "x" on type "Y".` | call `graphql_schema`, correct the operation |
45
+ | `__schema` or `__type` | `GRAPHQL_VALIDATION_FAILED` | graphql's introspection message | `Use graphql_schema to read the schema.` |
46
+ | a mutation in `graphql_query` | `MCP_OPERATION_NOT_ALLOWED` | `A mutation cannot run in graphql_query.` | use `graphql_mutate` |
47
+ | a query in `graphql_mutate` | `MCP_OPERATION_NOT_ALLOWED` | `A query cannot run in graphql_mutate.` | use `graphql_query` |
48
+ | a subscription | `SUBSCRIPTION_NOT_SUPPORTED` | `Subscriptions are not available over MCP.` | send a query |
49
+ | `@defer` or `@stream` | `INCREMENTAL_NOT_SUPPORTED` | `@defer is not available over MCP.` | remove the directive |
50
+ | a limit, cost or rate refusal, a bad variable | graxia's own | graxia's message | graxia's fix |
51
+ | a plugin answered with its own response | the plugin's, when its body has `errors` | the plugin's | the plugin's |
52
+ | a plugin response with no `errors`, shutdown | `MCP_EXECUTION_REFUSED` | the `graxia.execute` message | `Retry later; if it persists, the server is shutting down or a plugin refused the request.` |
53
+
54
+ The typed tools add `MCP_UNKNOWN_ARGUMENT` ([troubleshooting](../troubleshooting.md)), and `auth` adds
55
+ `MCP_UNAUTHORIZED`, `MCP_INSUFFICIENT_SCOPE` and `MCP_TOKEN_IN_URL`
56
+ ([troubleshooting auth](../troubleshooting-auth.md)). `McpErrorCode` (an exported type) is the union
57
+ of the codes `@graxia/mcp` emits.
58
+
59
+ `operationName` picks the operation: only the selected one is checked against the tool's kind, so a
60
+ document holding a query and a mutation runs its query in `graphql_query`.
61
+
62
+ ## `graphql_mutate`
63
+
64
+ Listed only with `mutations: true`; same input. A query is refused with a fix pointing to
65
+ `graphql_query`. With `mutations` off the tool does not exist: calling it is a JSON-RPC error
66
+ (`Tool graphql_mutate not found`). With `auth`, it is listed only for a token with the write scope
67
+ (`mcp:write` by default), and a read-only token calling it gets a 403 step-up
68
+ ([auth](./auth.md#scopes-and-step-up)).
69
+
70
+ ## Results
71
+
72
+ ```json
73
+ { "data": { "books": [{ "title": "Dune" }] } }
74
+ ```
75
+
76
+ - `structuredContent` is the GraphQL result (`{ data?, errors? }`); `content[0].text` is the same JSON.
77
+ - `isError` is `true` when there is no `data` (the operation did not run, or failed before any
78
+ field). A result with `data` and field `errors` is not an error call: the agent reads `errors`.
79
+ - Every error has `extensions.code` and `extensions.fix`. A masked failure keeps graxia's
80
+ `INTERNAL_SERVER_ERROR` code and its fix ("Retry later; quote the correlationId…"); the message
81
+ and cause never leak.
82
+
83
+ ## Trusted documents
84
+
85
+ With `trustedDocuments` in `strict` mode (the default in production) graxia runs no document a
86
+ client writes, and neither does the MCP server: `graphql_query` and `graphql_mutate` are **not
87
+ listed**, and a call answers `Only persisted documents are allowed.` with the code
88
+ `PERSISTED_QUERY_ONLY` and a fix naming the typed tools the caller has. `graphql_schema` stays.
89
+ The [typed tools](./operations.md) of `operations` run: they are the documents you persisted.
90
+ Without `operations` a strict server boots with `graphql_schema` alone, so nothing can be run:
91
+ `createMcp` reports it once through `onError` ("graxia runs trusted documents in strict mode and
92
+ `operations` gives no tool"). Pass `operations`. In `mixed` mode the generic tools are unchanged.
93
+
94
+ ## Cost of `can`
95
+
96
+ The caller view is built lazily, by the tool that needs it: `initialize`, `ping`, notifications
97
+ and `tools/list` never build it. Without `can` it is computed once, on the first tool call. With
98
+ `can`, it is computed on every tool call (the schema is printed and rebuilt for that caller's
99
+ permissions). It is cheap for a small schema; for a large one, keep `can` fast and expect a few
100
+ milliseconds per request. With `operations` the view decides which typed tools exist, so
101
+ `tools/list` and every `tools/call` build it (still once for all callers without `can`);
102
+ `initialize`, `ping` and notifications still do not.
@@ -0,0 +1,32 @@
1
+ # Roadmap
2
+
3
+ Where `@graxia/mcp` is going, as what you get. A direction, not a commitment.
4
+
5
+ ## Now
6
+
7
+ - **Follow-ups from the first release** — sharper refusals: a nesting overflow answers with the fix
8
+ to flatten the query ([#90](https://github.com/softistx/graxia/issues/90)), and `allowedHosts`
9
+ entries are normalised at boot as a request's host is
10
+ ([#93](https://github.com/softistx/graxia/issues/93)).
11
+
12
+ ## Not planned
13
+
14
+ - Stateful sessions and a server-to-client stream.
15
+ - Subscriptions over MCP.
16
+
17
+ ## Shipped
18
+
19
+ ### 0.1.0
20
+
21
+ - **Streamable HTTP and the generic tools** — `createMcp(graxia, { name })` with
22
+ `graphql_schema`, `graphql_query` and, on request, `graphql_mutate`, with an origin and host
23
+ check, CORS for allowed origins and graxia's limits and codes on every refusal.
24
+
25
+ - **OAuth resource server** — protected resource metadata (`mcp.metadata`), `WWW-Authenticate`
26
+ challenges, `verifyToken`, `mcp:read` and `mcp:write` scopes with step-up, and the principal in
27
+ `can` and `mcpAuth()`.
28
+
29
+ - **Persisted operations as typed tools** — `operations: { documents: manifest }` turns each
30
+ persisted query (and mutation, on request) into a tool with a JSON Schema for its arguments and
31
+ its result; under strict trusted documents they are the only tools that run operations, and
32
+ `genericTools: false` offers nothing else.
@@ -0,0 +1,101 @@
1
+ # Troubleshooting auth
2
+
3
+ The answers of `auth` ([the auth guide](./guide/auth.md)) and its boot errors, each headed by the
4
+ message or code you see. Everything else is in [troubleshooting](./troubleshooting.md).
5
+
6
+ ## 401 `Unauthorized: no bearer token.` (`MCP_UNAUTHORIZED`)
7
+
8
+ Header: `WWW-Authenticate: Bearer resource_metadata="…", scope="mcp:read"`.
9
+
10
+ `auth` is set and the request has no `Authorization: Bearer <token>`. A client with OAuth support
11
+ follows `resource_metadata` to the authorization server; otherwise send the token yourself. Another
12
+ scheme is not read: `Authorization: DPoP …` gets this answer too (DPoP is not supported).
13
+
14
+ ## 401 `Unauthorized: the access token is invalid.` (`MCP_UNAUTHORIZED`)
15
+
16
+ Header: `WWW-Authenticate: Bearer error="invalid_token", …`, as for the next five entries.
17
+
18
+ `verifyToken` resolved `undefined`: it does not know the token (a bad signature, another issuer,
19
+ revoked). Get a new token from the authorization server.
20
+
21
+ ## 401 `Unauthorized: the access token has expired.`
22
+
23
+ The `expiresAt` your verifier returned is in the past. Refresh the token.
24
+
25
+ ## 401 `Unauthorized: the access token was issued for another resource.`
26
+
27
+ The `audience` your verifier returned does not contain `auth.resource` (a fragment and one trailing
28
+ slash are ignored). The client must ask for a token for the same URL as `auth.resource` (the
29
+ `resource` parameter, RFC 8707). Check the `aud` claim of the token first.
30
+
31
+ ## 401 `Unauthorized: the access token carries no audience.`
32
+
33
+ `verifyToken` returned no `audience`, and the audience is checked by default. Return the token's
34
+ `aud`, or, when your verifier already refuses tokens issued for another resource, opt out with
35
+ `audience: 'verifier'` ([the auth guide](./guide/auth.md#audience)).
36
+
37
+ ## 401 `Unauthorized: the verifier returned an unusable expiry (expiresAt is in seconds).`
38
+
39
+ `onError` got `createMcp: verifyToken returned expiresAt …, and expiresAt is in seconds since the
40
+ epoch`. `expiresAt` is not a finite number or is above 1e11, which is a date in milliseconds.
41
+ Return the `exp` claim as is, or `Math.floor(date.getTime() / 1000)`; leave it out when the token
42
+ has no expiry.
43
+
44
+ ## 401 `Unauthorized: the verifier returned no scopes.`
45
+
46
+ `onError` got `createMcp: verifyToken must return scopes`. The info has no `scopes` array: return
47
+ `{ scopes: [...] }`, an empty list for a token with none.
48
+
49
+ ## 503 `The access token could not be verified: the token verifier failed.`
50
+
51
+ With `Retry-After: 5`. `verifyToken` threw (an introspection endpoint or a key store is down); the
52
+ error went to `onError`. A throw is an outage, never a 401: resolve `undefined` for a bad token.
53
+
54
+ **Every expired token answers 503: your verifier throws on a bad token.** A JWT library that
55
+ rejects an expired, badly signed or wrong-audience token by throwing (jose's `jwtVerify`) turns
56
+ each of them into a 503 the client retries instead of refreshing its token. Catch the library's
57
+ invalid-token errors in `verifyToken` and resolve `undefined`; rethrow the rest (a JWKS fetch, an
58
+ introspection call), as in [the auth guide](./guide/auth.md#verifytoken).
59
+
60
+ ## A 401 or 503 whose body is not JSON-RPC
61
+
62
+ `verifyToken` resolved a `Response` (a verifier that builds its own refusals): it is sent as is.
63
+ Read that library's documentation for its meaning.
64
+
65
+ ## `Forbidden: the token lacks mcp:read.` (`MCP_INSUFFICIENT_SCOPE`)
66
+
67
+ A 403 with `error="insufficient_scope", scope="mcp:read"`. Ask the authorization server for
68
+ `mcp:read` (or your `scopes.read`).
69
+
70
+ ## `Forbidden: graphql_mutate needs the scope mcp:write.` (`MCP_INSUFFICIENT_SCOPE`)
71
+
72
+ A 403 with `error="insufficient_scope", scope="mcp:read mcp:write"`. The message names the tool
73
+ called, so a typed tool answers `Forbidden: rename_book needs the scope mcp:write.`. A read-only token called a tool that writes from a stale
74
+ tool list. Re-authorize with both scopes (the challenge's `scope`); these tools are not listed for
75
+ a token without `mcp:write`. With `mutations` off there is no 403: the call gets
76
+ `Tool graphql_mutate not found`. A mutation tool `can` hides from the caller gets no 403 either,
77
+ and in strict trusted-documents mode `graphql_mutate` answers `PERSISTED_QUERY_ONLY`, not the 403.
78
+
79
+ ## `createMcp: auth.resource must be an absolute URL (got "…").`
80
+
81
+ Thrown by `createMcp` at startup. Pass the public URL of the MCP endpoint, scheme included:
82
+ `resource: 'https://api.example.com/mcp'`.
83
+
84
+ ## `createMcp: auth.resource must have no query and no fragment (got "…").`
85
+
86
+ Thrown at startup. A resource identifier is the endpoint's URL alone (RFC 8707): remove the `?…`
87
+ and the `#…`.
88
+
89
+ ## `createMcp: auth.authorizationServers is empty.`
90
+
91
+ Thrown at startup. List the issuer URL of the authorization server that issues the tokens:
92
+ `authorizationServers: ['https://auth.example.com']`.
93
+
94
+ ## `createMcp: auth.authorizationServers must hold absolute URLs (got "…").`
95
+
96
+ Thrown at startup. Every entry is an issuer URL with its scheme (`https://auth.example.com`, not
97
+ `auth.example.com`).
98
+
99
+ ## 400 `The access token is in the query string.` (`MCP_TOKEN_IN_URL`)
100
+
101
+ `?access_token=…` is refused (OAuth 2.1). Send `Authorization: Bearer <token>`.