@yhuan416/mcp-kit 0.0.0-stage → 0.1.1

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 (52) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +134 -2
  4. package/dist/env.cjs +128 -0
  5. package/dist/env.cjs.map +1 -0
  6. package/dist/env.d.cts +41 -0
  7. package/dist/env.d.ts +41 -0
  8. package/dist/env.js +119 -0
  9. package/dist/env.js.map +1 -0
  10. package/dist/http/index.cjs +682 -0
  11. package/dist/http/index.cjs.map +1 -0
  12. package/dist/http/index.d.cts +119 -0
  13. package/dist/http/index.d.ts +119 -0
  14. package/dist/http/index.js +670 -0
  15. package/dist/http/index.js.map +1 -0
  16. package/dist/index.cjs +482 -0
  17. package/dist/index.cjs.map +1 -0
  18. package/dist/index.d.cts +131 -0
  19. package/dist/index.d.ts +131 -0
  20. package/dist/index.js +454 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/info/index.cjs +404 -0
  23. package/dist/info/index.cjs.map +1 -0
  24. package/dist/info/index.d.cts +47 -0
  25. package/dist/info/index.d.ts +47 -0
  26. package/dist/info/index.js +391 -0
  27. package/dist/info/index.js.map +1 -0
  28. package/dist/testing/client.cjs +57 -0
  29. package/dist/testing/client.cjs.map +1 -0
  30. package/dist/testing/client.d.cts +34 -0
  31. package/dist/testing/client.d.ts +34 -0
  32. package/dist/testing/client.js +54 -0
  33. package/dist/testing/client.js.map +1 -0
  34. package/dist/testing/conformance.cjs +120 -0
  35. package/dist/testing/conformance.cjs.map +1 -0
  36. package/dist/testing/conformance.d.cts +26 -0
  37. package/dist/testing/conformance.d.ts +26 -0
  38. package/dist/testing/conformance.js +115 -0
  39. package/dist/testing/conformance.js.map +1 -0
  40. package/dist/types-D6AKhA-v.d.cts +95 -0
  41. package/dist/types-D6AKhA-v.d.ts +95 -0
  42. package/dist/types-DU3WHzhD.d.cts +76 -0
  43. package/dist/types-DU3WHzhD.d.ts +76 -0
  44. package/docs/contracts/env.md +77 -0
  45. package/docs/contracts/http.md +167 -0
  46. package/docs/contracts/info.md +135 -0
  47. package/docs/contracts/result.md +109 -0
  48. package/docs/contracts/tools.md +140 -0
  49. package/docs/migration.md +133 -0
  50. package/docs/release.md +106 -0
  51. package/docs/security.md +79 -0
  52. package/package.json +111 -4
@@ -0,0 +1,76 @@
1
+ import * as node_http from 'node:http';
2
+
3
+ interface InfoEndpointSpec {
4
+ path?: string;
5
+ auth?: string;
6
+ desc?: string;
7
+ }
8
+ interface InfoSnippet {
9
+ title: string;
10
+ code: string;
11
+ }
12
+ interface InfoIntegration {
13
+ hint?: string;
14
+ snippets?: InfoSnippet[];
15
+ }
16
+ type InfoSection = Record<string, unknown>;
17
+ interface ServiceInfo {
18
+ contract: string;
19
+ service: string;
20
+ version: string;
21
+ summary?: string;
22
+ build?: string;
23
+ git?: string;
24
+ deployment?: InfoSection;
25
+ storage?: InfoSection;
26
+ limits?: InfoSection;
27
+ endpoints?: Record<string, string | InfoEndpointSpec>;
28
+ integration?: InfoIntegration;
29
+ changelog?: string;
30
+ changelog_path?: string;
31
+ labels?: Record<string, string>;
32
+ [key: string]: unknown;
33
+ }
34
+ interface BuildServiceInfoOptions {
35
+ service: string;
36
+ version: string;
37
+ summary?: string;
38
+ build?: string;
39
+ git?: string;
40
+ deployment?: InfoSection | (() => InfoSection);
41
+ storage?: InfoSection | (() => InfoSection);
42
+ limits?: InfoSection | (() => InfoSection);
43
+ endpoints?: Record<string, string | InfoEndpointSpec> | (() => Record<string, string | InfoEndpointSpec>);
44
+ integration?: InfoIntegration | (() => InfoIntegration);
45
+ labels?: Record<string, string>;
46
+ changelogPath?: string;
47
+ changelogLines?: number;
48
+ extra?: Record<string, unknown>;
49
+ /** Recompute dynamic sections on every call. Result is merged last. */
50
+ dynamic?: () => Record<string, unknown>;
51
+ }
52
+ interface DirStats {
53
+ files: number;
54
+ sizeBytes: number;
55
+ entries: number;
56
+ truncated: boolean;
57
+ }
58
+ type HeaderSource = {
59
+ headers: Headers;
60
+ } | {
61
+ headers: Record<string, string | string[] | undefined>;
62
+ };
63
+ interface ResolvePublicUrlOptions {
64
+ publicUrl?: string;
65
+ envUrl?: string;
66
+ req?: HeaderSource;
67
+ fallback?: string;
68
+ }
69
+ interface InfoEndpoint {
70
+ contract: string;
71
+ version: string;
72
+ build(): ServiceInfo;
73
+ handle(req: node_http.IncomingMessage, res: node_http.ServerResponse): void;
74
+ }
75
+
76
+ export type { BuildServiceInfoOptions as B, DirStats as D, HeaderSource as H, InfoEndpoint as I, ResolvePublicUrlOptions as R, ServiceInfo as S, InfoEndpointSpec as a, InfoIntegration as b, InfoSection as c, InfoSnippet as d };
@@ -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,167 @@
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
+ - With a token configured, `allowAnonymous: true` also lets requests without a
37
+ valid token through as the configured `clientId` (or `anonymous`). Use it only
38
+ for genuinely public deployments.
39
+
40
+ Prefer `NAME_FILE` for container secrets:
41
+
42
+ ```bash
43
+ MY_SERVICE_HTTP_TOKEN_FILE=/run/secrets/mcp_token
44
+ ```
45
+
46
+ ## Host and Origin
47
+
48
+ For loopback binds with a known port, the kit generates a default allowlist:
49
+
50
+ ```text
51
+ Host: 127.0.0.1:8787, localhost:8787, [::1]:8787
52
+ Origin: http://127.0.0.1:8787, http://localhost:8787, http://[::1]:8787
53
+ ```
54
+
55
+ Override with:
56
+
57
+ ```bash
58
+ MY_SERVICE_HTTP_ALLOWED_HOSTS=example.com,10.0.0.5:8787
59
+ MY_SERVICE_HTTP_ALLOWED_ORIGINS=https://app.example.com
60
+ ```
61
+
62
+ Requests with a disallowed Host/Origin receive `403`. Requests without an
63
+ `Origin` header pass (non-browser MCP clients usually omit it).
64
+
65
+ ## Status codes
66
+
67
+ | Status | Meaning |
68
+ | --- | --- |
69
+ | `200` | Success |
70
+ | `206` | Partial content (Range) |
71
+ | `400` | Bad request/path |
72
+ | `401` | Missing or invalid token |
73
+ | `403` | Host/Origin rejected |
74
+ | `404` | Unknown path or file |
75
+ | `405` | Method not allowed |
76
+ | `413` | Request body too large |
77
+ | `415` | Unsupported content type |
78
+ | `416` | Invalid Range |
79
+ | `500` | Unexpected server error |
80
+ | `503` | Readiness check failed |
81
+
82
+ MCP routes use JSON-RPC error bodies. Non-MCP routes use:
83
+
84
+ ```json
85
+ { "ok": false, "error": { "code": "NOT_FOUND", "message": "not found" } }
86
+ ```
87
+
88
+ ## Body limit
89
+
90
+ Default: 4 MiB. Override with `bodyLimit`. POSTs over the limit receive `413`
91
+ before parsing or creating a server instance.
92
+
93
+ ## File downloads
94
+
95
+ Never accept a filesystem path from the URL. Use an opaque id and a resolver:
96
+
97
+ ```ts
98
+ files: {
99
+ resolve: (id) => lookupDump(id) ?? null,
100
+ downloadName: (id) => `dump-${id}.bin`,
101
+ }
102
+ ```
103
+
104
+ The resolver must return an absolute path inside your controlled storage, or
105
+ `null`. The id is a single URL segment: encoded separators (`%2F`, `%5C`) are
106
+ rejected. The handler supports `HEAD`, `Range`, `Content-Disposition`, and
107
+ `Accept-Ranges`.
108
+
109
+ ## Static files and UI
110
+
111
+ ```ts
112
+ webDir: new URL("./web/", import.meta.url).pathname,
113
+ vendor: {
114
+ "/vendor/xterm.js": { file: "vendor/xterm.js", type: "text/javascript" },
115
+ },
116
+ static: {
117
+ path: "/static",
118
+ root: "/srv/assets",
119
+ extensions: [".png", ".css"],
120
+ },
121
+ ```
122
+
123
+ - `/` serves `webDir/index.html`.
124
+ - Vendor assets are an explicit whitelist, not a directory listing.
125
+ - `static` resolves paths inside `root` and rejects traversal.
126
+ - UI assets are unauthenticated by default; put data behind `/api/*`.
127
+
128
+ ## App API
129
+
130
+ ```ts
131
+ apiHandler: async (req, res, url) => {
132
+ if (url.pathname === "/api/status") {
133
+ res.writeHead(200, { "content-type": "application/json" });
134
+ res.end(JSON.stringify({ ok: true }));
135
+ return true;
136
+ }
137
+ return false;
138
+ };
139
+ ```
140
+
141
+ `/api/*` uses the same auth as `/mcp`. The handler is called for every HTTP
142
+ method; return `false` for unhandled routes and let the handler send `405` when a
143
+ method is not supported.
144
+
145
+ ## Lifecycle
146
+
147
+ - `runHttp` installs SIGINT/SIGTERM handlers by default.
148
+ - Pass `handleSignals: false` when embedding or testing.
149
+ - Shutdown closes the HTTP server (waiting up to `shutdownTimeoutMs`, default
150
+ 5000 ms, then forcing open connections closed), the MCP handler, and then
151
+ calls `onShutdown`.
152
+ - `createHttpServer` returns a non-listening server plus `close()`; `close()`
153
+ is idempotent and closes the server when it is listening.
154
+
155
+ ## Creating a server per request
156
+
157
+ MCP 2026-07-28 is stateless. `createServer` is called for each request/probe:
158
+
159
+ ```ts
160
+ const manager = createManager();
161
+
162
+ await runHttp({
163
+ createServer: () => buildServer({ name, version, tools: buildTools(manager) }),
164
+ });
165
+ ```
166
+
167
+ Keep shared state in `manager`, not in module globals.
@@ -0,0 +1,135 @@
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. The kit re-applies
33
+ `contract`, `service`, and `version` after `extra`/`dynamic`, so those three
34
+ cannot be overridden by service data.
35
+
36
+ ## Sections
37
+
38
+ The page uses five sections; omit a section if it does not apply.
39
+
40
+ | Section | Answers | Examples |
41
+ | --- | --- | --- |
42
+ | `deployment` | What is running, where, since when | `runtime`, `platform`, `transport`, `publicUrl`, `listen`, `startedAt`, `uptimeSeconds`, `image`, `auth` |
43
+ | `storage` | Where data lives, how big, retention | directory paths, file counts, `cacheTtlDays` |
44
+ | `limits` | Hard limits and caps | `bodyBytes`, `tools`, `retainBytes`, `segmentBytes`, `flushMs` |
45
+ | `endpoints` | Paths, auth, purpose | `{ "/mcp": { path, auth, desc } }` |
46
+ | `integration` | How to connect | `{ hint, snippets: [{ title, code }] }` |
47
+
48
+ Optional `changelog` carries the top lines of a changelog file.
49
+
50
+ ## Units
51
+
52
+ Use raw numbers with a unit suffix; the renderer formats them.
53
+
54
+ | Suffix | Unit | JSON | Page |
55
+ | --- | --- | --- | --- |
56
+ | `*Bytes` | bytes | `4194304` | `4.0 MiB` |
57
+ | `*Ms` | milliseconds | `500` | `500 ms` |
58
+ | `*Seconds` | seconds | `2337` | `38m` |
59
+ | `*Days` | days | `7` | `7 days` |
60
+ | `baudMax` | baud | `5000000` | `5,000,000 baud` |
61
+
62
+ Do not pre-format values into strings in new code.
63
+
64
+ ## Public URL
65
+
66
+ `deployment.publicUrl` is resolved in this order:
67
+
68
+ 1. explicit `publicUrl`;
69
+ 2. `publicUrlEnv` environment variable;
70
+ 3. the request `Host` header (plus `X-Forwarded-Proto`);
71
+ 4. `fallbackPublicUrl`.
72
+
73
+ Do not build it from `os.hostname()`: in a container that is a meaningless
74
+ container id.
75
+
76
+ ## Content negotiation
77
+
78
+ | Request | Response |
79
+ | --- | --- |
80
+ | `GET /info` with `Accept: */*` | JSON |
81
+ | `GET /info` with `Accept: text/html` | HTML |
82
+ | `GET /info?format=json` | JSON |
83
+ | `GET /info?format=html` | HTML |
84
+
85
+ Responses set `Vary: Accept`, `Cache-Control: no-store`, and `Content-Length`.
86
+
87
+ ## Labels
88
+
89
+ JSON keys stay English and stable. HTML labels default to English and can be
90
+ overridden:
91
+
92
+ ```ts
93
+ createInfoEndpoint({
94
+ service: "my-service",
95
+ version: "1.0.0",
96
+ labels: { localStore: "Local store" },
97
+ });
98
+ ```
99
+
100
+ ## Security
101
+
102
+ `/info` and `service_info` are unauthenticated:
103
+
104
+ - never include tokens, passwords, private keys, or connection strings;
105
+ - report where a secret comes from (for example `MY_SERVICE_HTTP_TOKEN`), never
106
+ its value;
107
+ - directory paths are fine; sensitive filenames are not;
108
+ - the HTML renderer escapes all values.
109
+
110
+ ## Example
111
+
112
+ ```ts
113
+ const info = createInfoEndpoint({
114
+ service: "my-service",
115
+ version: "1.0.0",
116
+ summary: "A production MCP service",
117
+ publicUrlEnv: "MY_SERVICE_PUBLIC_URL",
118
+ startedAt: STARTED_AT,
119
+ endpoints: {
120
+ mcp: { path: "/mcp", auth: "Bearer", desc: "MCP endpoint" },
121
+ health: { path: "/health", auth: "none", desc: "Liveness" },
122
+ info: { path: "/info", auth: "none", desc: "Self-description" },
123
+ },
124
+ deployment: { transport: "http" },
125
+ limits: { bodyBytes: 4 * 1024 * 1024 },
126
+ integration: {
127
+ snippets: [
128
+ { title: "MCP client", code: '{"type":"http","url":"http://host:8787/mcp"}' },
129
+ ],
130
+ },
131
+ });
132
+
133
+ await runHttp({ createServer, info });
134
+ tools.push(info.tool());
135
+ ```
@@ -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,140 @@
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 (codepoint order) before registration and
127
+ rejects duplicate visible names. Do not rely on registration order for
128
+ `tools/list`.
129
+
130
+ ## Conformance
131
+
132
+ ```ts
133
+ import { checkToolDefinitions, assertConformant } from "@yhuan416/mcp-kit/conformance";
134
+
135
+ const issues = checkToolDefinitions(tools);
136
+ assertConformant(issues, { allowWarnings: true });
137
+ ```
138
+
139
+ The check covers names, descriptions, schemas, annotations, duplicates, and the
140
+ presence of `service_info`.