@niwa-labs/mcp 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The MCP surface that exposes niwa actions to agents.
package/package.json CHANGED
@@ -1,6 +1,15 @@
1
1
  {
2
2
  "name": "@niwa-labs/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts"
8
+ },
9
+ "dependencies": {
10
+ "@modelcontextprotocol/sdk": "^1.32.2",
11
+ "@niwa-labs/client": "0.0.0",
12
+ "@niwa-labs/core": "0.0.0",
13
+ "zod": "^4.6.7"
14
+ }
15
+ }
package/src/bind.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * bind.ts — the core client of one MCP session.
3
+ *
4
+ * The caller is bound by the transport, never by a tool argument:
5
+ * the client is opened with an id made from the session, so the host sees that id and no other.
6
+ */
7
+
8
+ import { connect } from "@niwa-labs/client";
9
+ import type { NiwaApi } from "@niwa-labs/client";
10
+ import type { Token } from "@niwa-labs/core";
11
+
12
+ /** The id of one MCP session. */
13
+ export type SessionId = string;
14
+
15
+ /** A session and the core client that speaks for it. */
16
+ export interface Binding {
17
+ readonly sessionId: SessionId;
18
+ readonly api: NiwaApi;
19
+ }
20
+
21
+ /** The client id the host sees for a session. */
22
+ export function clientIdOf(sessionId: SessionId): string {
23
+ return `mcp:${sessionId}`;
24
+ }
25
+
26
+ /** How the core client of a session is opened: by connecting to the host of the home. */
27
+ export type Connector = (opts: { home: string; id: string; token?: Token }) => Promise<NiwaApi>;
28
+
29
+ /** Open the core client of one session. */
30
+ export async function bind(opts: { home: string; sessionId: SessionId; token?: Token; connect?: Connector }): Promise<Binding> {
31
+ const api = await (opts.connect ?? connect)({
32
+ home: opts.home,
33
+ id: clientIdOf(opts.sessionId),
34
+ ...(opts.token === undefined ? {} : { token: opts.token }),
35
+ });
36
+ return { sessionId: opts.sessionId, api };
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,387 @@
1
+ /**
2
+ * index.ts — the MCP server: a thin client of the core.
3
+ *
4
+ * It keeps no list of actions: tools are built from `describe()` on every list and every call.
5
+ * The caller is the MCP session: one core client per session, opened with the session's id and
6
+ * closed when the session ends. A tool argument that names somebody else is only an argument.
7
+ */
8
+
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import type { Readable, Writable } from "node:stream";
11
+
12
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
13
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14
+ import {
15
+ CallToolRequestSchema,
16
+ ListToolsRequestSchema,
17
+ type CallToolResult,
18
+ } from "@modelcontextprotocol/sdk/types.js";
19
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
20
+
21
+ import { z } from "zod";
22
+
23
+ import { actionName, JsonSchemaValue, recordTypeName, seq } from "@niwa-labs/core";
24
+ import type { JsonSchema, Token } from "@niwa-labs/core";
25
+ import { HostError, RECORDS_READ_ACTION, RecordsOutput, withWorkingDirectory } from "@niwa-labs/client";
26
+ import { bind, type Binding, type Connector, type SessionId } from "./bind.ts";
27
+ import {
28
+ OPEN_QUESTIONS,
29
+ SUBMIT_ANSWER,
30
+ TASK_ASSIGNED,
31
+ TASK_FINISH,
32
+ WRAPPED_INPUT,
33
+ catalogOf,
34
+ withAssignedTasks,
35
+ withOpenQuestions,
36
+ } from "./tools.ts";
37
+ import type { AssignedTask, OpenQuestion, Tool } from "./tools.ts";
38
+
39
+ export { catalogOf } from "./tools.ts";
40
+ export type { Catalog, Tool } from "./tools.ts";
41
+
42
+ /**
43
+ * What the server tells an agent that connects: where the skill is, since the tools say what they
44
+ * do and not how niwa is used. The harness shows it with the tools.
45
+ */
46
+ export const INSTRUCTIONS = [
47
+ "niwa is the owner's local agent host. How to use it: run `niwa skill` (prints the skill).",
48
+ "To install the skill for yourself: `niwa skill install --harness <your harness kind>`.",
49
+ ].join("\n");
50
+
51
+ /** The MCP surface of one home, serving one transport. */
52
+ export interface McpServer {
53
+ readonly server: Server;
54
+ connect(transport: Transport): Promise<void>;
55
+ /** Close the server and the core client of its session. */
56
+ close(): Promise<void>;
57
+ }
58
+
59
+ /** What the MCP server of one home is given. */
60
+ export interface McpServerOptions {
61
+ readonly home: string;
62
+ /** The actions the session may see; without it, every action. */
63
+ readonly visible?: readonly string[];
64
+ /**
65
+ * The mark the server was given (`NIWA_SESSION_MARK`): it names the session the server serves,
66
+ * so the tool that answers a question can carry the exact schema of its open questions.
67
+ */
68
+ readonly mark?: string;
69
+ /** Who the server is: the token of the session it serves (`NIWA_ID`), else the owner's. */
70
+ readonly token?: Token;
71
+ /** How the core client of a session is opened; by default, by connecting to the host of the home. */
72
+ readonly connect?: Connector;
73
+ /** How often a session that may not read the journal looks at its tools again, in milliseconds; less often while they do not change. */
74
+ readonly refreshMs?: number;
75
+ }
76
+
77
+ /** Build the MCP server of one home. */
78
+ export function createMcpServer(opts: McpServerOptions): McpServer {
79
+ // A server serves one transport, so one connection: its fallback session id is its own.
80
+ const connectionId = randomUUID();
81
+ const bindings = new Map<SessionId, Promise<Binding>>();
82
+ // Ended with the session: what waits between two looks at the tools stops waiting.
83
+ const stopped = new AbortController();
84
+ const server = new Server(
85
+ { name: "niwa", version: "0.1.0" },
86
+ { capabilities: { tools: { listChanged: true } }, instructions: INSTRUCTIONS },
87
+ );
88
+
89
+ const bindingOf = (sessionId: SessionId | undefined): Promise<Binding> => {
90
+ const id = sessionId ?? connectionId;
91
+ const known = bindings.get(id);
92
+ if (known !== undefined) return known;
93
+ // A session that ended opens nothing: its client would never be closed.
94
+ if (closed) return Promise.reject(new Error("the MCP session is closed"));
95
+ const opened = bind({
96
+ home: opts.home,
97
+ sessionId: id,
98
+ ...(opts.token === undefined ? {} : { token: opts.token }),
99
+ ...(opts.connect === undefined ? {} : { connect: opts.connect }),
100
+ });
101
+ bindings.set(id, opened);
102
+ // A failed connect is not kept: the next call tries again.
103
+ opened.catch(() => bindings.delete(id));
104
+ return opened;
105
+ };
106
+
107
+ const closeBindings = async (): Promise<void> => {
108
+ const open = [...bindings.values()];
109
+ bindings.clear();
110
+ const results = await Promise.allSettled(open.map(async (opened) => (await opened.catch(() => undefined))?.api.close()));
111
+ const failed = results.find((result) => result.status === "rejected");
112
+ if (failed?.status === "rejected") throw failed.reason;
113
+ };
114
+
115
+ // The session ends once, whoever ends it: the transport or a call to `close`. Both wait for the same cleanup.
116
+ let cleanup: Promise<void> | undefined;
117
+ const end = (): Promise<void> => {
118
+ closed = true;
119
+ stopped.abort();
120
+ void watching?.return?.();
121
+ return (cleanup ??= closeBindings());
122
+ };
123
+ server.onclose = () => void end().catch(() => undefined);
124
+
125
+ // The tools as the session sees them now, and the fingerprint of the last list the server
126
+ // gave out or looked at: the harness caches `tools[]`, so it is told only when this changes.
127
+ const shownTools = async (api: Binding["api"]) => {
128
+ const { tools, actions } = catalogOf(await api.describe(), opts.visible);
129
+ return exactFinishTool(api, await exactAnswerTool(api, tools, actions, opts.mark), actions);
130
+ };
131
+ let lastShown: string | undefined;
132
+
133
+ server.setRequestHandler(ListToolsRequestSchema, async (_request, extra) => {
134
+ const { api } = await bindingOf(extra.sessionId);
135
+ const tools = await shownTools(api);
136
+ lastShown = fingerprintOf(tools);
137
+ return { tools };
138
+ });
139
+
140
+ // The tools of a connection change with the registered workflows and the tasks it owes a result for,
141
+ // and, when the server serves a session, with the questions that session is asked. The server follows
142
+ // the records that open, answer, cancel or expire any of these, recomputes the tools on each, and sends
143
+ // `notifications/tools/list_changed` only when the fingerprint of the tools is not the last one.
144
+ //
145
+ // Following the journal is a read, so it needs the grant to read it. A session that does not have it
146
+ // looks at its tools again every `refreshMs`, less often while they stay as they are: it is told later,
147
+ // but it is told.
148
+ let watching: AsyncIterator<unknown> | undefined;
149
+ let closed = false;
150
+ const refreshMs = opts.refreshMs ?? REFRESH_MS;
151
+ const watched = opts.mark === undefined ? [...CATALOG_RECORDS, ...TASK_RECORDS] : TOOL_RECORDS;
152
+
153
+ /**
154
+ * Tell the client when the tools are not the ones it was last given. A client that was given none
155
+ * has nothing to be told: what it lists first is the baseline.
156
+ */
157
+ const refresh = async (api: Binding["api"]): Promise<void> => {
158
+ const now = fingerprintOf(await shownTools(api));
159
+ const before = lastShown;
160
+ lastShown = now;
161
+ if (before !== undefined && now !== before) await server.sendToolListChanged();
162
+ };
163
+
164
+ const follow = async (api: Binding["api"]): Promise<void> => {
165
+ // Where to follow from: the end of the journal as the host reads it now, with no record of the
166
+ // history sent back. The baseline is taken after it, so a record that lands in between is only
167
+ // seen twice, and the second sight changes nothing.
168
+ const read = RecordsOutput.parse(await api.call(RECORDS_READ_ACTION, { types: watched, tail: 1 }));
169
+ const live = api.records.since({ from: seq(read.next), types: watched })[Symbol.asyncIterator]();
170
+ watching = live;
171
+ if (closed) return void live.return?.();
172
+ // What changed before that position, after the client listed its tools, is not in the feed.
173
+ await refresh(api);
174
+ for (let next = await live.next(); !next.done; next = await live.next()) {
175
+ // A list that cannot be made now is made again at the next record.
176
+ await refresh(api).catch(() => undefined);
177
+ }
178
+ };
179
+
180
+ const poll = async (api: Binding["api"]): Promise<void> => {
181
+ await refresh(api);
182
+ // Every look at the tools is a call of the session, and the host records the calls of a session: a
183
+ // session whose tools do not change looks less and less often, and again at the full rate after a change.
184
+ let wait = refreshMs;
185
+ while (!closed) {
186
+ await pause(wait, stopped.signal);
187
+ if (closed) break;
188
+ const before = lastShown;
189
+ await refresh(api).catch(() => undefined);
190
+ wait = lastShown === before ? Math.min(wait * 2, refreshMs * IDLE_LOOKS) : refreshMs;
191
+ }
192
+ };
193
+
194
+ const watch = async (): Promise<void> => {
195
+ const { api } = await bindingOf(undefined);
196
+ try {
197
+ await follow(api);
198
+ } catch (error) {
199
+ // Only a refusal of the grant is answered by looking again; a host that is gone leaves things as they were.
200
+ if (error instanceof HostError && error.denied !== undefined) await poll(api);
201
+ }
202
+ };
203
+ server.oninitialized = () => {
204
+ // A watch that fails leaves the server as it was: the harness still lists tools on connect.
205
+ void watch().catch(() => undefined);
206
+ };
207
+
208
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
209
+ const binding = await bindingOf(extra.sessionId);
210
+ try {
211
+ return answer(await callTool(binding, request.params.name, request.params.arguments ?? {}, opts.visible));
212
+ } catch (error) {
213
+ return { content: [{ type: "text", text: errorText(error) }], isError: true };
214
+ }
215
+ });
216
+
217
+ return {
218
+ server,
219
+ connect: (transport) => server.connect(transport),
220
+ async close(): Promise<void> {
221
+ try {
222
+ await server.close();
223
+ } finally {
224
+ await end();
225
+ }
226
+ },
227
+ };
228
+ }
229
+
230
+ /**
231
+ * The tools, with the one that answers a question carrying the exact schema of the open
232
+ * questions of the session the server serves.
233
+ *
234
+ * A server with no mark, a session with no open question, or a host that cannot say (no
235
+ * sessions module) shows the tool as the action declares it.
236
+ */
237
+ async function exactAnswerTool(
238
+ api: Binding["api"],
239
+ tools: readonly Tool[],
240
+ actions: ReadonlyMap<string, string>,
241
+ mark: string | undefined,
242
+ ): Promise<Tool[]> {
243
+ const index = tools.findIndex((tool) => actions.get(tool.name) === SUBMIT_ANSWER);
244
+ if (mark === undefined || index === -1) return [...tools];
245
+ let questions: OpenQuestion[];
246
+ try {
247
+ const listed = OpenQuestionsOutput.parse(await api.call(actionName(OPEN_QUESTIONS), { mark }));
248
+ questions = listed.questions;
249
+ } catch {
250
+ return [...tools];
251
+ }
252
+ return tools.map((tool, at) => (at === index ? withOpenQuestions(tool, questions) : tool));
253
+ }
254
+
255
+ /** The records that open or close a question of a session, or say which session a mark names. */
256
+ const QUESTION_RECORDS = ["session.marked", "request.created", "request.answered", "request.cancelled", "request.expired"].map(recordTypeName);
257
+
258
+ /** The records that open or close a task, and so change what the caller owes a result for. */
259
+ const TASK_RECORDS = ["task.created", "task.done"].map(recordTypeName);
260
+
261
+ /** The records that add, check again or promote a workflow, which is the tool `flow_<id>`. */
262
+ const CATALOG_RECORDS = ["workflow.registered", "workflow.rechecked", "workflow.builtin.promoted"].map(recordTypeName);
263
+
264
+ /** Every record after which the tools of a session may be other than they were. */
265
+ const TOOL_RECORDS = [...QUESTION_RECORDS, ...TASK_RECORDS, ...CATALOG_RECORDS];
266
+
267
+ /** How often a session that may not read the journal looks at its tools again, in milliseconds. */
268
+ const REFRESH_MS = 3_000;
269
+
270
+ /** The most a session whose tools do not change spaces its looks: this many times `REFRESH_MS`. */
271
+ const IDLE_LOOKS = 10;
272
+
273
+ /** Wait this long, or until the signal says to stop waiting. */
274
+ function pause(ms: number, signal: AbortSignal): Promise<void> {
275
+ return new Promise((resolve) => {
276
+ if (signal.aborted) return resolve();
277
+ const done = (): void => {
278
+ clearTimeout(timer);
279
+ signal.removeEventListener("abort", done);
280
+ resolve();
281
+ };
282
+ const timer = setTimeout(done, ms);
283
+ signal.addEventListener("abort", done, { once: true });
284
+ });
285
+ }
286
+
287
+ /** A short hash of the tools as they are listed: equal when no schema, name or description moved. */
288
+ function fingerprintOf(tools: unknown): string {
289
+ return createHash("sha256").update(JSON.stringify(tools)).digest("hex");
290
+ }
291
+
292
+ /**
293
+ * The tools, with the one that finishes a task carrying the exact result schema of the open tasks
294
+ * the caller is responsible for.
295
+ *
296
+ * A caller that is not shown `task.finish` or `task.assigned`, a caller that owes no result, and a host
297
+ * that cannot say (no tasks module) all get the tool as the action declares it.
298
+ */
299
+ async function exactFinishTool(
300
+ api: Binding["api"],
301
+ tools: readonly Tool[],
302
+ actions: ReadonlyMap<string, string>,
303
+ ): Promise<Tool[]> {
304
+ const index = tools.findIndex((tool) => actions.get(tool.name) === TASK_FINISH);
305
+ // The caller asks only what it may see: a session that was not shown `task.assigned` is not made to be denied it.
306
+ if (index === -1 || ![...actions.values()].includes(TASK_ASSIGNED)) return [...tools];
307
+ let tasks: AssignedTask[];
308
+ try {
309
+ tasks = AssignedTasksOutput.parse(await api.call(actionName(TASK_ASSIGNED), {})).tasks;
310
+ } catch {
311
+ return [...tools];
312
+ }
313
+ return tools.map((tool, at) => (at === index ? withAssignedTasks(tool, tasks) : tool));
314
+ }
315
+
316
+ /** What `task.assigned` answers, as this surface reads it. */
317
+ const AssignedTasksOutput = z.object({
318
+ tasks: z.array(
319
+ z.object({ task: z.string().min(1), description: z.string(), result: JsonSchemaValue.optional() }),
320
+ ),
321
+ });
322
+
323
+ /** What `session.open-questions` answers, as this surface reads it. */
324
+ const OpenQuestionsOutput = z.object({
325
+ questions: z.array(z.object({ request: z.string().min(1), schema: JsonSchemaValue })),
326
+ });
327
+
328
+ function errorText(error: unknown): string {
329
+ // A refusal by a grant says whose grant and which rule is missing, so the agent can ask for it.
330
+ if (error instanceof HostError && error.denied !== undefined) {
331
+ return `${error.message}\n${JSON.stringify({ denied: { grant: error.denied.grant, missing: error.denied.missing } })}`;
332
+ }
333
+ return error instanceof Error ? error.message : String(error);
334
+ }
335
+
336
+ function answer(value: unknown): CallToolResult {
337
+ return { content: [{ type: "text", text: JSON.stringify(value ?? null, null, 2) }] };
338
+ }
339
+
340
+ /** Run one tool for the session of `binding`; throws when the call fails. */
341
+ async function callTool(
342
+ binding: Binding,
343
+ name: string,
344
+ args: Record<string, unknown>,
345
+ visible: readonly string[] | undefined,
346
+ ): Promise<unknown> {
347
+ const { api } = binding;
348
+ const catalog = catalogOf(await api.describe(), visible);
349
+ // A tool the session may not see is not a tool at all: the call is refused by name.
350
+ if (!catalog.tools.some((tool) => tool.name === name)) {
351
+ throw new Error(`there is no tool "${name}"`);
352
+ }
353
+ const action = catalog.actions.get(name);
354
+ if (action === undefined) throw new Error(`there is no tool "${name}"`);
355
+ // An action that takes no object has its input in `input`.
356
+ if (catalog.wrapped.has(name)) return api.call(action, args[WRAPPED_INPUT]);
357
+ // The session works where its server was started: an action that takes a directory is told so when the model names none.
358
+ const input = catalog.tools.find((tool) => tool.name === name)?.inputSchema;
359
+ return api.call(action, withWorkingDirectory(input as JsonSchema | undefined, args));
360
+ }
361
+
362
+ /** The streams of a stdio server: the process's own unless a caller gives others. */
363
+ export interface StdioStreams {
364
+ readonly stdin: Readable;
365
+ readonly stdout: Writable;
366
+ }
367
+
368
+ /**
369
+ * Run the MCP server of one home over stdio, until its client goes away.
370
+ *
371
+ * The SDK's stdio transport ends on an error of its input but not on its end: the harness closing
372
+ * the pipe would leave the server, and the connection it holds to the host, running. So the end of the
373
+ * input ends the server.
374
+ */
375
+ export async function serveMcp(opts: McpServerOptions, streams: StdioStreams = { stdin: process.stdin, stdout: process.stdout }): Promise<McpServer> {
376
+ const mcp = createMcpServer(opts);
377
+ await mcp.connect(new StdioServerTransport(streams.stdin, streams.stdout));
378
+ const gone = (): void => void mcp.close().catch(() => undefined);
379
+ streams.stdin.once("end", gone);
380
+ streams.stdin.once("close", gone);
381
+ mcp.server.onclose = ((previous) => () => {
382
+ streams.stdin.off("end", gone);
383
+ streams.stdin.off("close", gone);
384
+ previous?.();
385
+ })(mcp.server.onclose);
386
+ return mcp;
387
+ }