@yhuan416/mcp-kit 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.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +134 -2
- package/dist/env.cjs +114 -0
- package/dist/env.cjs.map +1 -0
- package/dist/env.d.cts +41 -0
- package/dist/env.d.ts +41 -0
- package/dist/env.js +105 -0
- package/dist/env.js.map +1 -0
- package/dist/http/index.cjs +567 -0
- package/dist/http/index.cjs.map +1 -0
- package/dist/http/index.d.cts +118 -0
- package/dist/http/index.d.ts +118 -0
- package/dist/http/index.js +555 -0
- package/dist/http/index.js.map +1 -0
- package/dist/index.cjs +460 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +131 -0
- package/dist/index.d.ts +131 -0
- package/dist/index.js +432 -0
- package/dist/index.js.map +1 -0
- package/dist/info/index.cjs +376 -0
- package/dist/info/index.cjs.map +1 -0
- package/dist/info/index.d.cts +47 -0
- package/dist/info/index.d.ts +47 -0
- package/dist/info/index.js +363 -0
- package/dist/info/index.js.map +1 -0
- package/dist/testing/client.cjs +53 -0
- package/dist/testing/client.cjs.map +1 -0
- package/dist/testing/client.d.cts +33 -0
- package/dist/testing/client.d.ts +33 -0
- package/dist/testing/client.js +50 -0
- package/dist/testing/client.js.map +1 -0
- package/dist/testing/conformance.cjs +117 -0
- package/dist/testing/conformance.cjs.map +1 -0
- package/dist/testing/conformance.d.cts +26 -0
- package/dist/testing/conformance.d.ts +26 -0
- package/dist/testing/conformance.js +112 -0
- package/dist/testing/conformance.js.map +1 -0
- package/dist/types-D6AKhA-v.d.cts +95 -0
- package/dist/types-D6AKhA-v.d.ts +95 -0
- package/dist/types-DU3WHzhD.d.cts +76 -0
- package/dist/types-DU3WHzhD.d.ts +76 -0
- package/docs/contracts/env.md +77 -0
- package/docs/contracts/http.md +159 -0
- package/docs/contracts/info.md +133 -0
- package/docs/contracts/result.md +109 -0
- package/docs/contracts/tools.md +139 -0
- package/docs/migration.md +133 -0
- package/docs/release.md +106 -0
- package/docs/security.md +77 -0
- package/package.json +111 -4
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Environment contract
|
|
2
|
+
|
|
3
|
+
Use one service prefix for every variable, for example `SERIAL_HUB_MCP_` or
|
|
4
|
+
`MY_SERVICE_`. The kit provides parsing and secret helpers; the service decides
|
|
5
|
+
which variables it reads.
|
|
6
|
+
|
|
7
|
+
## Standard variables
|
|
8
|
+
|
|
9
|
+
| Variable | Default | Purpose |
|
|
10
|
+
| --- | --- | --- |
|
|
11
|
+
| `<PREFIX>_HTTP_HOST` | `127.0.0.1` | Bind address |
|
|
12
|
+
| `<PREFIX>_HTTP_PORT` | `8787` | Bind port |
|
|
13
|
+
| `<PREFIX>_HTTP_PATH` | `/mcp` | MCP endpoint |
|
|
14
|
+
| `<PREFIX>_HTTP_TOKEN` | unset | Bearer token |
|
|
15
|
+
| `<PREFIX>_HTTP_TOKEN_FILE` | unset | File containing the token |
|
|
16
|
+
| `<PREFIX>_PUBLIC_URL` | unset | URL shown on `/info` |
|
|
17
|
+
| `<PREFIX>_HTTP_ALLOWED_HOSTS` | loopback defaults | Comma-separated Host allowlist |
|
|
18
|
+
| `<PREFIX>_HTTP_ALLOWED_ORIGINS` | loopback defaults | Comma-separated Origin allowlist |
|
|
19
|
+
| `<PREFIX>_HTTP_BODY_LIMIT` | `4194304` | Request body bytes |
|
|
20
|
+
| `<PREFIX>_HTTP_UI` | `1` | Enable the optional web UI |
|
|
21
|
+
| `<PREFIX>_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` |
|
|
22
|
+
| `<PREFIX>_DATA_DIR` | service-specific | Persistent data root |
|
|
23
|
+
|
|
24
|
+
## Secrets
|
|
25
|
+
|
|
26
|
+
`readSecret` implements the `NAME` / `NAME_FILE` convention:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { readSecret } from "@yhuan416/mcp-kit/env";
|
|
30
|
+
|
|
31
|
+
const token = readSecret("MY_SERVICE_HTTP_TOKEN");
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Rules:
|
|
35
|
+
|
|
36
|
+
- `NAME` wins over `NAME_FILE`.
|
|
37
|
+
- A missing `NAME_FILE` target or an empty file is an error, never a silent
|
|
38
|
+
empty token.
|
|
39
|
+
- Docker/Kubernetes secrets should be mounted as files.
|
|
40
|
+
- Never log the value; use `maskSecret` when echoing.
|
|
41
|
+
|
|
42
|
+
## Parsing
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { envBool, envInt, envList } from "@yhuan416/mcp-kit/env";
|
|
46
|
+
|
|
47
|
+
const port = envInt("MY_SERVICE_HTTP_PORT", { fallback: 8787, min: 0, max: 65535 });
|
|
48
|
+
const ui = envBool("MY_SERVICE_HTTP_UI", { fallback: true });
|
|
49
|
+
const hosts = envList("MY_SERVICE_HTTP_ALLOWED_HOSTS");
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Invalid values throw at startup. Do not silently fall back to a default when the
|
|
53
|
+
operator supplied a malformed value.
|
|
54
|
+
|
|
55
|
+
## Allowlists
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { buildHttpAllowlist } from "@yhuan416/mcp-kit/env";
|
|
59
|
+
|
|
60
|
+
const allow = buildHttpAllowlist({
|
|
61
|
+
host: "127.0.0.1",
|
|
62
|
+
port: 8787,
|
|
63
|
+
envPrefix: "MY_SERVICE",
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- Explicit `*_HTTP_ALLOWED_HOSTS` / `*_HTTP_ALLOWED_ORIGINS` win.
|
|
68
|
+
- Loopback host plus a known port generates loopback defaults.
|
|
69
|
+
- Port `0` (ephemeral) does not generate defaults.
|
|
70
|
+
|
|
71
|
+
## Rules
|
|
72
|
+
|
|
73
|
+
1. One prefix per service; do not mix prefixes.
|
|
74
|
+
2. Secrets come from env or files, never command-line arguments.
|
|
75
|
+
3. Validate numeric/boolean values at startup.
|
|
76
|
+
4. Document every variable in the service README.
|
|
77
|
+
5. `_FILE` variants are preferred in containers.
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# HTTP and auth contract
|
|
2
|
+
|
|
3
|
+
`runHttp` exposes one MCP endpoint plus a small set of operational endpoints.
|
|
4
|
+
|
|
5
|
+
## Endpoints
|
|
6
|
+
|
|
7
|
+
| Path | Method | Auth | Purpose |
|
|
8
|
+
| --- | --- | --- | --- |
|
|
9
|
+
| `/mcp` | POST/GET/DELETE | Bearer | MCP Streamable HTTP |
|
|
10
|
+
| `/health` | GET/HEAD | none | Liveness; cheap, no dependency checks |
|
|
11
|
+
| `/ready` | GET/HEAD | none | Optional readiness; `503` when not ready |
|
|
12
|
+
| `/info` | GET/HEAD | none | `info/1` JSON or HTML |
|
|
13
|
+
| `/files/<id>` | GET/HEAD | Bearer | Opaque file download, supports Range |
|
|
14
|
+
| `/static/<path>` | GET/HEAD | configurable | Optional static directory |
|
|
15
|
+
| `/api/*` | app-defined | Bearer | Optional app API |
|
|
16
|
+
| `/` | GET/HEAD | none | Optional static web UI |
|
|
17
|
+
|
|
18
|
+
`/health`, `/ready`, and `/info` must never include secrets.
|
|
19
|
+
|
|
20
|
+
## Authentication
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
await runHttp({
|
|
24
|
+
createServer,
|
|
25
|
+
auth: { token: process.env.MY_SERVICE_HTTP_TOKEN!, clientId: "local" },
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- Token is compared in constant time.
|
|
30
|
+
- `auth.token` may be replaced by `auth: (req) => AuthInfo | false` for custom
|
|
31
|
+
verification.
|
|
32
|
+
- Validated `AuthInfo` is attached to the request and appears in
|
|
33
|
+
`ctx.auth` / `ctx.principal`.
|
|
34
|
+
- **Loopback binds may run without auth. Non-loopback binds require auth unless
|
|
35
|
+
`allowAnonymous: true` is set explicitly.**
|
|
36
|
+
|
|
37
|
+
Prefer `NAME_FILE` for container secrets:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
MY_SERVICE_HTTP_TOKEN_FILE=/run/secrets/mcp_token
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Host and Origin
|
|
44
|
+
|
|
45
|
+
For loopback binds with a known port, the kit generates a default allowlist:
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
Host: 127.0.0.1:8787, localhost:8787, [::1]:8787
|
|
49
|
+
Origin: http://127.0.0.1:8787, http://localhost:8787, http://[::1]:8787
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Override with:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
MY_SERVICE_HTTP_ALLOWED_HOSTS=example.com,10.0.0.5:8787
|
|
56
|
+
MY_SERVICE_HTTP_ALLOWED_ORIGINS=https://app.example.com
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Requests with a disallowed Host/Origin receive `403`. Requests without an
|
|
60
|
+
`Origin` header pass (non-browser MCP clients usually omit it).
|
|
61
|
+
|
|
62
|
+
## Status codes
|
|
63
|
+
|
|
64
|
+
| Status | Meaning |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `200` | Success |
|
|
67
|
+
| `206` | Partial content (Range) |
|
|
68
|
+
| `400` | Bad request/path |
|
|
69
|
+
| `401` | Missing or invalid token |
|
|
70
|
+
| `403` | Host/Origin rejected |
|
|
71
|
+
| `404` | Unknown path or file |
|
|
72
|
+
| `405` | Method not allowed |
|
|
73
|
+
| `413` | Request body too large |
|
|
74
|
+
| `415` | Unsupported content type |
|
|
75
|
+
| `416` | Invalid Range |
|
|
76
|
+
| `500` | Unexpected server error |
|
|
77
|
+
| `503` | Readiness check failed |
|
|
78
|
+
|
|
79
|
+
MCP routes use JSON-RPC error bodies. Non-MCP routes use:
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
{ "ok": false, "error": { "code": "NOT_FOUND", "message": "not found" } }
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Body limit
|
|
86
|
+
|
|
87
|
+
Default: 4 MiB. Override with `bodyLimit`. POSTs over the limit receive `413`
|
|
88
|
+
before parsing or creating a server instance.
|
|
89
|
+
|
|
90
|
+
## File downloads
|
|
91
|
+
|
|
92
|
+
Never accept a filesystem path from the URL. Use an opaque id and a resolver:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
files: {
|
|
96
|
+
resolve: (id) => lookupDump(id) ?? null,
|
|
97
|
+
downloadName: (id) => `dump-${id}.bin`,
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The resolver must return an absolute path inside your controlled storage, or
|
|
102
|
+
`null`. The handler supports `HEAD`, `Range`, `Content-Disposition`, and
|
|
103
|
+
`Accept-Ranges`.
|
|
104
|
+
|
|
105
|
+
## Static files and UI
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
webDir: new URL("./web/", import.meta.url).pathname,
|
|
109
|
+
vendor: {
|
|
110
|
+
"/vendor/xterm.js": { file: "vendor/xterm.js", type: "text/javascript" },
|
|
111
|
+
},
|
|
112
|
+
static: {
|
|
113
|
+
path: "/static",
|
|
114
|
+
root: "/srv/assets",
|
|
115
|
+
extensions: [".png", ".css"],
|
|
116
|
+
},
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- `/` serves `webDir/index.html`.
|
|
120
|
+
- Vendor assets are an explicit whitelist, not a directory listing.
|
|
121
|
+
- `static` resolves paths inside `root` and rejects traversal.
|
|
122
|
+
- UI assets are unauthenticated by default; put data behind `/api/*`.
|
|
123
|
+
|
|
124
|
+
## App API
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
apiHandler: async (req, res, url) => {
|
|
128
|
+
if (url.pathname === "/api/status") {
|
|
129
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
130
|
+
res.end(JSON.stringify({ ok: true }));
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
return false;
|
|
134
|
+
};
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`/api/*` uses the same auth as `/mcp`. Return `false` for unhandled routes.
|
|
138
|
+
|
|
139
|
+
## Lifecycle
|
|
140
|
+
|
|
141
|
+
- `runHttp` installs SIGINT/SIGTERM handlers by default.
|
|
142
|
+
- Pass `handleSignals: false` when embedding or testing.
|
|
143
|
+
- Shutdown closes the HTTP server, the MCP handler, and then calls
|
|
144
|
+
`onShutdown`.
|
|
145
|
+
- `createHttpServer` returns a non-listening server plus `close()`.
|
|
146
|
+
|
|
147
|
+
## Creating a server per request
|
|
148
|
+
|
|
149
|
+
MCP 2026-07-28 is stateless. `createServer` is called for each request/probe:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const manager = createManager();
|
|
153
|
+
|
|
154
|
+
await runHttp({
|
|
155
|
+
createServer: () => buildServer({ name, version, tools: buildTools(manager) }),
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Keep shared state in `manager`, not in module globals.
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Service info contract (`info/1`)
|
|
2
|
+
|
|
3
|
+
A deployed MCP service should explain itself: what it is, which version is
|
|
4
|
+
running, where data lives, what limits apply, and how to connect.
|
|
5
|
+
|
|
6
|
+
The same data is used by:
|
|
7
|
+
|
|
8
|
+
- `GET /info` (JSON for scripts, HTML for humans);
|
|
9
|
+
- the MCP `service_info` tool.
|
|
10
|
+
|
|
11
|
+
## Shape
|
|
12
|
+
|
|
13
|
+
```json
|
|
14
|
+
{
|
|
15
|
+
"contract": "info/1",
|
|
16
|
+
"service": "serial-hub-mcp",
|
|
17
|
+
"version": "0.3.4",
|
|
18
|
+
"summary": "Serial port MCP server and hub",
|
|
19
|
+
"build": "2026-11-28T10:00:00Z",
|
|
20
|
+
"git": "abc1234",
|
|
21
|
+
"deployment": {},
|
|
22
|
+
"storage": {},
|
|
23
|
+
"limits": {},
|
|
24
|
+
"endpoints": {},
|
|
25
|
+
"integration": {},
|
|
26
|
+
"labels": {},
|
|
27
|
+
"changelog": "..."
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`contract` is required and currently `"info/1"`. Add fields freely; do not
|
|
32
|
+
rename or change the meaning of the core fields.
|
|
33
|
+
|
|
34
|
+
## Sections
|
|
35
|
+
|
|
36
|
+
The page uses five sections; omit a section if it does not apply.
|
|
37
|
+
|
|
38
|
+
| Section | Answers | Examples |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `deployment` | What is running, where, since when | `runtime`, `platform`, `transport`, `publicUrl`, `listen`, `startedAt`, `uptimeSeconds`, `image`, `auth` |
|
|
41
|
+
| `storage` | Where data lives, how big, retention | directory paths, file counts, `cacheTtlDays` |
|
|
42
|
+
| `limits` | Hard limits and caps | `bodyBytes`, `tools`, `retainBytes`, `segmentBytes`, `flushMs` |
|
|
43
|
+
| `endpoints` | Paths, auth, purpose | `{ "/mcp": { path, auth, desc } }` |
|
|
44
|
+
| `integration` | How to connect | `{ hint, snippets: [{ title, code }] }` |
|
|
45
|
+
|
|
46
|
+
Optional `changelog` carries the top lines of a changelog file.
|
|
47
|
+
|
|
48
|
+
## Units
|
|
49
|
+
|
|
50
|
+
Use raw numbers with a unit suffix; the renderer formats them.
|
|
51
|
+
|
|
52
|
+
| Suffix | Unit | JSON | Page |
|
|
53
|
+
| --- | --- | --- | --- |
|
|
54
|
+
| `*Bytes` | bytes | `4194304` | `4.0 MiB` |
|
|
55
|
+
| `*Ms` | milliseconds | `500` | `500 ms` |
|
|
56
|
+
| `*Seconds` | seconds | `2337` | `38m` |
|
|
57
|
+
| `*Days` | days | `7` | `7 days` |
|
|
58
|
+
| `baudMax` | baud | `5000000` | `5,000,000 baud` |
|
|
59
|
+
|
|
60
|
+
Do not pre-format values into strings in new code.
|
|
61
|
+
|
|
62
|
+
## Public URL
|
|
63
|
+
|
|
64
|
+
`deployment.publicUrl` is resolved in this order:
|
|
65
|
+
|
|
66
|
+
1. explicit `publicUrl`;
|
|
67
|
+
2. `publicUrlEnv` environment variable;
|
|
68
|
+
3. the request `Host` header (plus `X-Forwarded-Proto`);
|
|
69
|
+
4. `fallbackPublicUrl`.
|
|
70
|
+
|
|
71
|
+
Do not build it from `os.hostname()`: in a container that is a meaningless
|
|
72
|
+
container id.
|
|
73
|
+
|
|
74
|
+
## Content negotiation
|
|
75
|
+
|
|
76
|
+
| Request | Response |
|
|
77
|
+
| --- | --- |
|
|
78
|
+
| `GET /info` with `Accept: */*` | JSON |
|
|
79
|
+
| `GET /info` with `Accept: text/html` | HTML |
|
|
80
|
+
| `GET /info?format=json` | JSON |
|
|
81
|
+
| `GET /info?format=html` | HTML |
|
|
82
|
+
|
|
83
|
+
Responses set `Vary: Accept`, `Cache-Control: no-store`, and `Content-Length`.
|
|
84
|
+
|
|
85
|
+
## Labels
|
|
86
|
+
|
|
87
|
+
JSON keys stay English and stable. HTML labels default to English and can be
|
|
88
|
+
overridden:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
createInfoEndpoint({
|
|
92
|
+
service: "my-service",
|
|
93
|
+
version: "1.0.0",
|
|
94
|
+
labels: { localStore: "Local store" },
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Security
|
|
99
|
+
|
|
100
|
+
`/info` and `service_info` are unauthenticated:
|
|
101
|
+
|
|
102
|
+
- never include tokens, passwords, private keys, or connection strings;
|
|
103
|
+
- report where a secret comes from (for example `MY_SERVICE_HTTP_TOKEN`), never
|
|
104
|
+
its value;
|
|
105
|
+
- directory paths are fine; sensitive filenames are not;
|
|
106
|
+
- the HTML renderer escapes all values.
|
|
107
|
+
|
|
108
|
+
## Example
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const info = createInfoEndpoint({
|
|
112
|
+
service: "my-service",
|
|
113
|
+
version: "1.0.0",
|
|
114
|
+
summary: "A production MCP service",
|
|
115
|
+
publicUrlEnv: "MY_SERVICE_PUBLIC_URL",
|
|
116
|
+
startedAt: STARTED_AT,
|
|
117
|
+
endpoints: {
|
|
118
|
+
mcp: { path: "/mcp", auth: "Bearer", desc: "MCP endpoint" },
|
|
119
|
+
health: { path: "/health", auth: "none", desc: "Liveness" },
|
|
120
|
+
info: { path: "/info", auth: "none", desc: "Self-description" },
|
|
121
|
+
},
|
|
122
|
+
deployment: { transport: "http" },
|
|
123
|
+
limits: { bodyBytes: 4 * 1024 * 1024 },
|
|
124
|
+
integration: {
|
|
125
|
+
snippets: [
|
|
126
|
+
{ title: "MCP client", code: '{"type":"http","url":"http://host:8787/mcp"}' },
|
|
127
|
+
],
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
await runHttp({ createServer, info });
|
|
132
|
+
tools.push(info.tool());
|
|
133
|
+
```
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Result and error contract
|
|
2
|
+
|
|
3
|
+
The kit has one result envelope for every tool call, regardless of transport.
|
|
4
|
+
|
|
5
|
+
## Success
|
|
6
|
+
|
|
7
|
+
```json
|
|
8
|
+
{
|
|
9
|
+
"ok": true,
|
|
10
|
+
"response": { "value": 42 },
|
|
11
|
+
"durationMs": 12
|
|
12
|
+
}
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- `response` is the business payload. It may be any JSON value.
|
|
16
|
+
- `durationMs` is added by the kit.
|
|
17
|
+
- MCP `isError` is `false`.
|
|
18
|
+
|
|
19
|
+
## Failure
|
|
20
|
+
|
|
21
|
+
```json
|
|
22
|
+
{
|
|
23
|
+
"ok": false,
|
|
24
|
+
"error": {
|
|
25
|
+
"code": "NOT_FOUND",
|
|
26
|
+
"message": "connection not found",
|
|
27
|
+
"details": { "connection_id": "abc" },
|
|
28
|
+
"retryable": false
|
|
29
|
+
},
|
|
30
|
+
"durationMs": 3
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- Business failures use MCP `isError: true`; they are **not** JSON-RPC errors.
|
|
35
|
+
- Protocol-level failures (bad JSON, unsupported method) remain JSON-RPC errors.
|
|
36
|
+
- `message` is for humans and agents. Keep it actionable.
|
|
37
|
+
- `details` is optional structured data.
|
|
38
|
+
- `retryable` tells clients whether an immediate retry can succeed.
|
|
39
|
+
|
|
40
|
+
## Assertions
|
|
41
|
+
|
|
42
|
+
Operations that verify device/service state can attach assertion failures:
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"ok": false,
|
|
47
|
+
"error": { "code": "ASSERTION_FAILED", "message": "register mismatch" },
|
|
48
|
+
"assert": {
|
|
49
|
+
"matched": false,
|
|
50
|
+
"failures": [
|
|
51
|
+
{ "path": "registers.status", "actual": 0, "expected": 1 }
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
"durationMs": 8
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Error codes
|
|
59
|
+
|
|
60
|
+
Use stable string codes. The kit ships these conventions; domains may add their
|
|
61
|
+
own prefixed codes.
|
|
62
|
+
|
|
63
|
+
| Code | Meaning |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `INVALID_ARGUMENT` | Input failed schema or semantic validation |
|
|
66
|
+
| `NOT_FOUND` | Requested resource does not exist |
|
|
67
|
+
| `ALREADY_EXISTS` | Resource already exists |
|
|
68
|
+
| `FAILED_PRECONDITION` | Current state does not allow the operation |
|
|
69
|
+
| `UNAUTHENTICATED` | Missing or invalid credentials |
|
|
70
|
+
| `PERMISSION_DENIED` | Authenticated but not allowed |
|
|
71
|
+
| `UNAVAILABLE` | Dependency/transport temporarily unavailable |
|
|
72
|
+
| `DEADLINE_EXCEEDED` | Operation exceeded its deadline |
|
|
73
|
+
| `CANCELLED` | Operation was cancelled |
|
|
74
|
+
| `ASSERTION_FAILED` | Post-condition/assertion mismatch |
|
|
75
|
+
| `INTERNAL` | Unexpected server error |
|
|
76
|
+
|
|
77
|
+
## Helpers
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { ok, fail, ToolCallError } from "@yhuan416/mcp-kit";
|
|
81
|
+
|
|
82
|
+
return ok({ value: 1 });
|
|
83
|
+
return fail("NOT_FOUND", "missing", { details: { id } });
|
|
84
|
+
|
|
85
|
+
throw new ToolCallError("FAILED_PRECONDITION", "port is busy", {
|
|
86
|
+
retryable: true,
|
|
87
|
+
assertFailures: [{ path: "state", actual: "open", expected: "closed" }],
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Raw MCP results
|
|
92
|
+
|
|
93
|
+
A handler may return a raw MCP result when it needs protocol features the kit
|
|
94
|
+
does not wrap (for example multi-round-trip `input_required`). The kit passes it
|
|
95
|
+
through unchanged.
|
|
96
|
+
|
|
97
|
+
## Validation errors
|
|
98
|
+
|
|
99
|
+
The MCP SDK validates `inputSchema` before the kit handler runs. Those failures
|
|
100
|
+
are returned as MCP tool errors by the SDK, so their text may use the SDK's
|
|
101
|
+
format. Direct calls through `invokeTool` (HTTP API, tests, web UI) use the kit's
|
|
102
|
+
`INVALID_ARGUMENT` envelope.
|
|
103
|
+
|
|
104
|
+
## Text and structure
|
|
105
|
+
|
|
106
|
+
For `0.1.x`, the envelope is returned as JSON text in `content[0].text`. This is
|
|
107
|
+
intentional: agents can read it, scripts can parse it, and clients that only
|
|
108
|
+
support text still work. `structuredContent` will be added when output schemas
|
|
109
|
+
are adopted consistently.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Tool contract
|
|
2
|
+
|
|
3
|
+
Every MCP tool is defined once with `defineTool` and registered with
|
|
4
|
+
`registerTools` (or `buildServer`). The same definition is used by the MCP
|
|
5
|
+
transport, HTTP APIs, and tests.
|
|
6
|
+
|
|
7
|
+
## Definition
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const tool = defineTool({
|
|
11
|
+
name: "search",
|
|
12
|
+
title: "Search",
|
|
13
|
+
description: "Search indexed documents. Read-only and safe to retry.",
|
|
14
|
+
inputSchema: z.object({ query: z.string().min(1) }),
|
|
15
|
+
outputSchema: z.object({ items: z.array(z.object({ id: z.string() })) }),
|
|
16
|
+
annotations: {
|
|
17
|
+
readOnlyHint: true,
|
|
18
|
+
destructiveHint: false,
|
|
19
|
+
idempotentHint: true,
|
|
20
|
+
openWorldHint: false,
|
|
21
|
+
},
|
|
22
|
+
hidden: false,
|
|
23
|
+
cache: { ttlMs: 30_000, scope: "private" },
|
|
24
|
+
handler: async (args, ctx) => ({ ok: true, response: { items: [] } }),
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Naming
|
|
29
|
+
|
|
30
|
+
- Prefer `lower_snake_case`: `serial_open`, `device_list`, `log_query`.
|
|
31
|
+
- Allowed characters in MCP: `A-Z a-z 0-9 _ - .`; max 128.
|
|
32
|
+
- Names must be stable. Renaming a tool is a breaking change for agents and
|
|
33
|
+
stored prompts.
|
|
34
|
+
- When a tool name is generic (`open`, `read`), the server name is the
|
|
35
|
+
namespace. Do not add a redundant prefix inside a single-purpose server.
|
|
36
|
+
|
|
37
|
+
## Description
|
|
38
|
+
|
|
39
|
+
A description must answer:
|
|
40
|
+
|
|
41
|
+
1. what the tool does;
|
|
42
|
+
2. whether it mutates state;
|
|
43
|
+
3. units and ranges for numeric arguments;
|
|
44
|
+
4. whether it is safe to retry.
|
|
45
|
+
|
|
46
|
+
Keep the first sentence short; clients often show only one line.
|
|
47
|
+
|
|
48
|
+
## Input schema
|
|
49
|
+
|
|
50
|
+
- `inputSchema` is required. Use `z.object({})` for no-argument tools.
|
|
51
|
+
- The schema is a [Standard Schema](https://standardschema.dev/) (zod 4, Valibot,
|
|
52
|
+
ArkType, or `fromJsonSchema`).
|
|
53
|
+
- Prefer explicit `describe()` on fields that are not self-explanatory.
|
|
54
|
+
- Never accept secrets as tool arguments. Read them from the environment.
|
|
55
|
+
- Use `*_id` for opaque identifiers, `*_ms` for millisecond values, and
|
|
56
|
+
`*_bytes` for byte counts.
|
|
57
|
+
|
|
58
|
+
## Output schema
|
|
59
|
+
|
|
60
|
+
`outputSchema` is optional. When provided, return a response that matches it.
|
|
61
|
+
The kit does not wrap structured content yet; the envelope is also available as
|
|
62
|
+
text for compatibility.
|
|
63
|
+
|
|
64
|
+
## Annotations
|
|
65
|
+
|
|
66
|
+
Set all four hints:
|
|
67
|
+
|
|
68
|
+
| Hint | Meaning |
|
|
69
|
+
| --- | --- |
|
|
70
|
+
| `readOnlyHint` | Does not modify state |
|
|
71
|
+
| `destructiveHint` | May delete/overwrite data |
|
|
72
|
+
| `idempotentHint` | Repeating with the same input is safe |
|
|
73
|
+
| `openWorldHint` | Interacts with external systems |
|
|
74
|
+
|
|
75
|
+
Missing annotations are a conformance warning.
|
|
76
|
+
|
|
77
|
+
## Hidden tools
|
|
78
|
+
|
|
79
|
+
`hidden: true` keeps a tool callable through `invokeTool` (for a web UI, HTTP
|
|
80
|
+
API, or tests) but does not register it with MCP. Use it for operations that are
|
|
81
|
+
too dangerous or too low-level for an agent.
|
|
82
|
+
|
|
83
|
+
## Handler context
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
handler: async (args, ctx) => {
|
|
87
|
+
ctx.transport; // "stdio" | "http"
|
|
88
|
+
ctx.requestId; // JSON-RPC request id
|
|
89
|
+
ctx.auth; // validated AuthInfo, when HTTP auth is configured
|
|
90
|
+
ctx.principal; // stable tenant/user identity
|
|
91
|
+
ctx.protocolVersion;
|
|
92
|
+
ctx.clientCapabilities;
|
|
93
|
+
ctx.signal; // request cancellation
|
|
94
|
+
ctx.logger;
|
|
95
|
+
ctx.trace; // traceparent/tracestate/baggage
|
|
96
|
+
ctx.http; // method/path/headers for HTTP requests
|
|
97
|
+
return { ok: true, response: ... };
|
|
98
|
+
};
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`ctx` is additive: existing handlers written as `(args) => ...` keep working.
|
|
102
|
+
|
|
103
|
+
## Queues
|
|
104
|
+
|
|
105
|
+
Use a queue when the underlying resource is not concurrency-safe:
|
|
106
|
+
|
|
107
|
+
- `serialQueue()` — one global lane;
|
|
108
|
+
- `keyedSerialQueue()` — one lane per key, concurrent across keys.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const queue = keyedSerialQueue();
|
|
112
|
+
|
|
113
|
+
buildServer({
|
|
114
|
+
name: "serial-hub",
|
|
115
|
+
version: "1.0.0",
|
|
116
|
+
tools,
|
|
117
|
+
queue,
|
|
118
|
+
key: (args, ctx) => `${ctx.principal ?? "anon"}:${args.connection_id}`,
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Always include the principal in the key when the server serves multiple users.
|
|
123
|
+
|
|
124
|
+
## Determinism
|
|
125
|
+
|
|
126
|
+
`registerTools` sorts tools by name before registration. Do not rely on
|
|
127
|
+
registration order for `tools/list`.
|
|
128
|
+
|
|
129
|
+
## Conformance
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { checkToolDefinitions, assertConformant } from "@yhuan416/mcp-kit/conformance";
|
|
133
|
+
|
|
134
|
+
const issues = checkToolDefinitions(tools);
|
|
135
|
+
assertConformant(issues, { allowWarnings: true });
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The check covers names, descriptions, schemas, annotations, duplicates, and the
|
|
139
|
+
presence of `service_info`.
|