@agentproto/mcp-server 0.2.0 → 0.2.2
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 +202 -1
- package/dist/index.mjs +2 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
package/LICENSE
CHANGED
|
@@ -1 +1,202 @@
|
|
|
1
|
-
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.mjs
CHANGED
|
@@ -146,10 +146,8 @@ function contentText(payload) {
|
|
|
146
146
|
}
|
|
147
147
|
function buildMcpTool(opts) {
|
|
148
148
|
const { tool, candidates } = opts;
|
|
149
|
-
const objectShape = asObjectShape(tool.inputSchema);
|
|
150
|
-
const inputShape = objectShape ?? {
|
|
151
|
-
input: tool.inputSchema
|
|
152
|
-
};
|
|
149
|
+
const objectShape = tool.inputSchema != null ? asObjectShape(tool.inputSchema) : void 0;
|
|
150
|
+
const inputShape = objectShape ?? (tool.inputSchema != null ? { input: tool.inputSchema } : {});
|
|
153
151
|
const resolveContext = async () => typeof opts.context === "function" ? await opts.context() : opts.context;
|
|
154
152
|
return {
|
|
155
153
|
name: opts.name ? mcpName(opts.name) : mcpName(tool.id),
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/self-inspect-tool.ts","../src/to-mcp-tool.ts","../src/index.ts"],"names":["join","z","contentText"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,eAAsB,gBAAA,CACpB,KACA,SAAA,EACqB;AACrB,EAAA,IAAI,OAAO,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AkB,GAAA,EAAK,EAAE,MAAA,EAAQ,CAAY,CAAA;AAAA,EACxD;AAEA,EAAA,OAAO,GAAA;AACT;AAIA,SAASE,aAAY,OAAA,EAEnB;AACA,EAAA,OAAO;AAAA,IACL,OAAA,EAAS;AAAA,MACP;AAAA,QACE,IAAA,EAAM,MAAA;AAAA,QACN,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAA,EAAS,MAAM,CAAC;AAAA;AACvC;AACF,GACF;AACF","file":"index.mjs","sourcesContent":["/**\n * self_inspect — MCP tool that lets an agent query its own AIP-42 manifest\n * without knowing its disk path.\n *\n * The agent supplies its logical `id`; the runtime resolves\n * `<workspace>/.agents/<id>/AGENT.md`, loads it via `agentVerbs`, resolves\n * each tool and routine ref to a `{ id, description }` summary, and returns\n * `{ agentPath, tools, routines }`.\n *\n * Injection mechanism: the workspace path is captured in the\n * `registerSelfInspectTool` closure at server-creation time (same pattern as\n * `registerFsTools`). The agent provides its logical id (known from its own\n * system-prompt frontmatter) — not an absolute path.\n */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { z } from \"zod\"\nimport { join } from \"node:path\"\nimport { agentVerbs } from \"@agentproto/agent\"\nimport { toolVerbs } from \"@agentproto/tool\"\nimport { routineVerbs } from \"@agentproto/routine\"\n\nexport interface RefSummary {\n id: string\n description: string\n}\n\nexport interface SelfInspectResult {\n agentPath: string\n tools: RefSummary[]\n routines: RefSummary[]\n}\n\n/**\n * Reduce one AIP-27 ref block (from an agent's `tools[]`) to `{id, description}`.\n *\n * - `file:` → load the TOOL.md and extract `id` + `description` from the handle.\n * `baseDir` is the workspace root (tools live at `<workspace>/tools/<id>/TOOL.md`\n * by the AIP-14 `pathOf` convention, or wherever the file pointer says).\n * - `inline:` → use the inline params directly.\n * - `ref:` or `string` → surface the ref identifier as the id (registry resolution\n * requires an external resolver not available here at inspect time).\n */\nexport async function summarizeToolRef(\n raw: unknown,\n workspace: string,\n): Promise<RefSummary> {\n if (typeof raw === \"string\") {\n return { id: raw, description: \"(string ref — not locally resolved)\" }\n }\n if (typeof raw !== \"object\" || raw === null) {\n return { id: String(raw), description: \"(unknown ref shape)\" }\n }\n const block = raw as { ref?: string; file?: string; inline?: Record<string, unknown> }\n if (block.file) {\n try {\n const handle = await toolVerbs.resolve(\n { file: block.file },\n { baseDir: workspace },\n )\n return { id: handle.id, description: handle.description ?? \"\" }\n } catch {\n return { id: block.file, description: \"(file ref — could not load)\" }\n }\n }\n if (block.inline) {\n return {\n id: String(block.inline.id ?? \"\"),\n description: String(block.inline.description ?? \"\"),\n }\n }\n if (block.ref) {\n return { id: block.ref, description: \"(ref — not locally resolved)\" }\n }\n return { id: JSON.stringify(raw), description: \"(unknown ref shape)\" }\n}\n\n/**\n * Same logic for AIP-41 routine refs. Routines live at\n * `<workspace>/.routines/<id>/ROUTINE.md` by `routineSpec.pathOf` convention.\n */\nexport async function summarizeRoutineRef(\n raw: unknown,\n workspace: string,\n): Promise<RefSummary> {\n if (typeof raw === \"string\") {\n return { id: raw, description: \"(string ref — not locally resolved)\" }\n }\n if (typeof raw !== \"object\" || raw === null) {\n return { id: String(raw), description: \"(unknown ref shape)\" }\n }\n const block = raw as { ref?: string; file?: string; inline?: Record<string, unknown> }\n if (block.file) {\n try {\n const handle = await routineVerbs.resolve(\n { file: block.file },\n { baseDir: workspace },\n )\n return { id: handle.id, description: handle.description ?? \"\" }\n } catch {\n return { id: block.file, description: \"(file ref — could not load)\" }\n }\n }\n if (block.inline) {\n return {\n id: String(block.inline.id ?? \"\"),\n description: String(block.inline.description ?? \"\"),\n }\n }\n if (block.ref) {\n return { id: block.ref, description: \"(ref — not locally resolved)\" }\n }\n return { id: JSON.stringify(raw), description: \"(unknown ref shape)\" }\n}\n\n/**\n * Core logic, extracted for testability.\n * Throws with `{ error, message }` on `agent_not_found`.\n */\nexport async function selfInspect(\n agentId: string,\n workspace: string,\n): Promise<SelfInspectResult> {\n const agentPath = join(workspace, \".agents\", agentId, \"AGENT.md\")\n\n let handle: Awaited<ReturnType<typeof agentVerbs.load>>[\"handle\"]\n try {\n const result = await agentVerbs.load(agentPath)\n handle = result.handle\n } catch (err) {\n const e = new Error(\n `No AGENT.md found for agent '${agentId}' at '${agentPath}'. ` +\n `Ensure an AGENT.md exists at <workspace>/.agents/${agentId}/AGENT.md.`,\n )\n ;(e as NodeJS.ErrnoException).code = \"agent_not_found\"\n throw e\n }\n\n const rawTools = (handle.tools ?? []) as unknown[]\n const rawRoutines = (handle.routines ?? []) as unknown[]\n\n const [tools, routines] = await Promise.all([\n Promise.all(rawTools.map((r) => summarizeToolRef(r, workspace))),\n Promise.all(rawRoutines.map((r) => summarizeRoutineRef(r, workspace))),\n ])\n\n return { agentPath, tools, routines }\n}\n\n/**\n * Register the `self_inspect` MCP tool on `server`.\n *\n * The workspace path is injected at registration time; the agent only needs to\n * supply its logical `id` at call time — not a disk path. This is called from\n * `createMcpServer` whenever a workspace is provided.\n */\nexport function registerSelfInspectTool(\n server: McpServer,\n opts: { workspace: string },\n): void {\n server.tool(\n \"self_inspect\",\n \"Return this agent's AIP-42 manifest summary (tools + routines) without requiring knowledge of disk paths. \" +\n \"Pass the agent's logical `id` (the `id:` field in its AGENT.md frontmatter); the runtime resolves it to \" +\n \"`<workspace>/.agents/<agentId>/AGENT.md`. Returns `{ agentPath, tools, routines }` — each item has at \" +\n \"minimum `{ id, description }`. File refs are loaded; string/ref refs are surfaced as-is.\",\n {\n agentId: z\n .string()\n .min(1)\n .describe(\n \"The agent's logical id (e.g. 'writer'). Matches the `id:` field in the AGENT.md frontmatter. \" +\n \"The runtime resolves this to `<workspace>/.agents/<agentId>/AGENT.md` — \" +\n \"you do not need to know the absolute disk path.\",\n ),\n },\n async ({ agentId }) => {\n try {\n const result = await selfInspect(agentId, opts.workspace)\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: \"agent_not_found\", message }, null, 2),\n },\n ],\n isError: true,\n }\n }\n },\n )\n}\n","/**\n * toMcpTool — expose an AIP-14 TOOL contract as a callable MCP tool whose body\n * is `runTool` (resolve DRIVER → validate → execute → validate). The mirror of\n * the Mastra `resolveTool` adapter: one TOOL handle, one resolver, three call\n * surfaces (CLI, agent, MCP) with no per-surface re-coding.\n *\n * Framework-only: it takes a handle + candidate DRIVERs and never knows what\n * the tool does. The injected per-call `context` (live capabilities such as a\n * warm browser session) is baked in at registration by the composition root —\n * an MCP client supplies only the tool's declared input, never context.\n */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { ZodRawShape, ZodType } from \"zod\"\nimport { runTool, type DriverHandle, type ResolverContext } from \"@agentproto/driver\"\nimport type { ToolContext, ToolHandle } from \"@agentproto/tool\"\n\nexport interface ToMcpToolOptions<\n TInput,\n TOutput,\n TContext extends ToolContext,\n> {\n /** The AIP-14 contract to expose. */\n tool: ToolHandle<TInput, TOutput, TContext>\n /** Candidate DRIVERs the resolver dispatches over. */\n candidates: readonly DriverHandle[]\n /**\n * Per-call injected context (live capabilities). A value, or a factory run\n * once per invocation (e.g. to lease a fresh session). Omit for context-free\n * tools (`report.render`).\n */\n context?:\n | TContext\n | (() => TContext | Promise<TContext>)\n /** Resolver routing hints (region, pinned provider, policy tags). */\n resolverContext?: ResolverContext\n /** Resolved secrets to inject into the DriverContext. */\n secrets?: Record<string, string>\n /** Override the advertised MCP tool name (default: tool id, `:`/`.`→`_`). */\n name?: string\n}\n\n/** What `buildMcpTool` produces — registerable on any McpServer, and directly\n * callable in tests without standing up a transport. */\nexport interface McpToolRegistration {\n name: string\n description: string\n inputShape: ZodRawShape\n handler: (args: Record<string, unknown>) => Promise<{\n content: Array<{ type: \"text\"; text: string }>\n }>\n}\n\n/** A ZodObject exposes a `.shape` raw-shape getter; everything else doesn't. */\nfunction asObjectShape(schema: ZodType): ZodRawShape | undefined {\n const shape = (schema as { shape?: unknown }).shape\n return shape && typeof shape === \"object\"\n ? (shape as ZodRawShape)\n : undefined\n}\n\nfunction mcpName(id: string): string {\n return id.replace(/[-:.]/g, \"_\")\n}\n\nfunction contentText(payload: unknown): {\n content: Array<{ type: \"text\"; text: string }>\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload, null, 2) }],\n }\n}\n\n/**\n * Build (but do not register) the MCP tool. When the contract's `inputSchema`\n * is an object schema, its fields become the MCP tool's parameters directly;\n * otherwise the input is taken under a single `input` parameter carrying the\n * whole schema.\n */\nexport function buildMcpTool<TInput, TOutput, TContext extends ToolContext>(\n opts: ToMcpToolOptions<TInput, TOutput, TContext>,\n): McpToolRegistration {\n const { tool, candidates } = opts\n const objectShape = asObjectShape(tool.inputSchema)\n const inputShape: ZodRawShape = objectShape ?? {\n input: tool.inputSchema,\n }\n\n const resolveContext = async (): Promise<unknown> =>\n typeof opts.context === \"function\"\n ? await (opts.context as () => TContext | Promise<TContext>)()\n : opts.context\n\n return {\n name: opts.name ? mcpName(opts.name) : mcpName(tool.id),\n description: tool.description,\n inputShape,\n handler: async (args) => {\n const input = objectShape ? args : (args.input as unknown)\n const context = await resolveContext()\n const output = await runTool({\n tool,\n candidates,\n input,\n context,\n resolverContext: opts.resolverContext,\n secrets: opts.secrets,\n })\n return contentText(output)\n },\n }\n}\n\n/**\n * Register a TOOL contract as a callable MCP tool on `server`, dispatching each\n * call through `runTool`. Returns the registration (handy for diagnostics /\n * tests). Once registered, the tool is callable from any MCP host with no\n * per-host code.\n */\nexport function toMcpTool<TInput, TOutput, TContext extends ToolContext>(\n server: McpServer,\n opts: ToMcpToolOptions<TInput, TOutput, TContext>,\n): McpToolRegistration {\n const reg = buildMcpTool(opts)\n server.tool(reg.name, reg.description, reg.inputShape, reg.handler)\n return reg\n}\n","/**\n * @agentproto/mcp-server — exposes AIP doctype verbs as MCP tools.\n *\n * Hand a list of `DoctypeSpec` instances (one per registered AIP) and\n * optionally a workspace dir; the server registers\n * `create_<name> / load_<name> / list_<name> / update_<name> /\n * resolve_<name> / delete_<name>` for each spec, including AIP-40\n * extensions auto-loaded from `<workspace>/extensions/<slug>/EXTENSION.md`.\n *\n * Two ways to run it:\n * 1. **Embedded** — call `createMcpServer({ specs, workspace })` and\n * attach to your own transport (stdio, websocket, …).\n * 2. **Standalone** — `runStdioServer({ specs, workspace })` wires\n * stdio for you. Useful as a `mcp_servers.<id>` config entry on\n * Claude Desktop / Cursor / any MCP host.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\"\nimport { z } from \"zod\"\nimport { existsSync } from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport { isAbsolute, join, resolve } from \"node:path\"\nimport { createVerbs, type DoctypeSpec } from \"@agentproto/manifest\"\nimport {\n parseExtensionManifest,\n specFromExtension,\n} from \"@agentproto/extension\"\nimport { registerSelfInspectTool } from \"./self-inspect-tool.js\"\n\n// `RegisterableSpec<TParams, THandle>` is just `DoctypeSpec` plus the\n// constraint that callers passing different generics across the array\n// must type-erase via `as unknown as DoctypeSpec<...>` at the boundary.\n// We don't try to express the heterogeneous list in TS — same trick\n// `@agentproto/driver`'s `implementations[]` uses.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnySpec = DoctypeSpec<any, any>\n\nexport interface CreateMcpServerOptions {\n /** Doctype specs registered as MCP tools. One per AIP. */\n specs: readonly AnySpec[]\n /**\n * Optional workspace dir. If provided, the server scans\n * `<workspace>/extensions/` for `EXTENSION.md` files and registers\n * each as a local doctype. The parent of each extension is resolved\n * by matching the extension's `extends:` field (`aip-N`) against\n * `specs.find(s => s.aip === N)` — so the spec list MUST include the\n * parents the extensions reference, else loading throws.\n */\n workspace?: string\n /** Server name advertised over MCP. Default `agentproto-mcp-server`. */\n name?: string\n /** Server version advertised over MCP. Default `0.1.0-alpha`. */\n version?: string\n}\n\nexport interface CreateMcpServerResult {\n /** The wired McpServer; attach a transport to start serving. */\n server: McpServer\n /**\n * The list of doctype names the server registered tools for —\n * useful for tests + diagnostics. Includes any extensions loaded\n * from `workspace/extensions/`.\n */\n registered: readonly string[]\n}\n\nexport async function createMcpServer(\n opts: CreateMcpServerOptions,\n): Promise<CreateMcpServerResult> {\n const server = new McpServer({\n name: opts.name ?? \"agentproto-mcp-server\",\n version: opts.version ?? \"0.1.0-alpha\",\n })\n\n const allSpecs: AnySpec[] = [...opts.specs]\n\n // Load extensions when a workspace is given.\n if (opts.workspace) {\n const extensions = await loadExtensions(opts.workspace, opts.specs)\n allSpecs.push(...extensions)\n }\n\n // Path-anchoring: when a workspace is set, resolve all relative\n // dir/path arguments against it. Agents pass logical paths like\n // \"tools\" or \"tools/echo/TOOL.md\"; the server pins them to the\n // workspace so they don't leak into process.cwd() (which is\n // wherever the host happened to spawn the server).\n const anchor = (p: string): string =>\n isAbsolute(p) || !opts.workspace ? p : join(opts.workspace, p)\n\n for (const spec of allSpecs) {\n registerVerbs(server, spec, anchor)\n }\n\n // self_inspect: contextual tool injected when a workspace is provided so\n // agents can query their own AIP-42 manifest by logical id — no disk path\n // knowledge required.\n if (opts.workspace) {\n registerSelfInspectTool(server, { workspace: opts.workspace })\n }\n\n return {\n server,\n registered: allSpecs.map((s) => s.name),\n }\n}\n\n/**\n * Wire `createMcpServer` to stdio for use as an `mcp_servers.<id>`\n * entry on Claude Desktop / Cursor / etc. Resolves once the\n * transport closes.\n */\nexport async function runStdioServer(\n opts: CreateMcpServerOptions,\n): Promise<void> {\n const { server } = await createMcpServer(opts)\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nexport {\n toMcpTool,\n buildMcpTool,\n type ToMcpToolOptions,\n type McpToolRegistration,\n} from \"./to-mcp-tool.js\"\nexport {\n registerSelfInspectTool,\n selfInspect,\n summarizeToolRef,\n summarizeRoutineRef,\n type RefSummary,\n type SelfInspectResult,\n} from \"./self-inspect-tool.js\"\n\n// ── verb registration ───────────────────────────────────────────────\n\nfunction registerVerbs(\n server: McpServer,\n spec: AnySpec,\n anchor: (p: string) => string,\n): void {\n const verbs = createVerbs(spec)\n // Tool name uses snake_case to match MCP convention; spec.name may\n // be kebab (driver-cli) or namespaced (acme:deal). Map all to snake.\n const verbName = (verb: string) =>\n `${verb}_${spec.name.replace(/[-:]/g, \"_\")}`\n const description = (verb: string, body: string) =>\n `${verb} the AIP-${spec.aip} ${spec.name} doctype. ${body}`\n\n // create\n server.tool(\n verbName(\"create\"),\n description(\n \"create\",\n \"Author a new manifest from params. Returns { path, rendered }.\",\n ),\n {\n params: z\n .record(z.string(), z.unknown())\n .describe(`The ${spec.name} definition fields.`),\n dir: z.string().describe(\"Workspace-relative or absolute target directory.\"),\n body: z\n .string()\n .optional()\n .describe(\"Markdown body after the frontmatter. Defaults to a stub.\"),\n dryRun: z\n .boolean()\n .optional()\n .describe(\"Render only — don't write to disk.\"),\n },\n async ({ params, dir, body, dryRun }) => {\n const result = await verbs.create(params, {\n dir: anchor(dir),\n body,\n dryRun,\n })\n return contentText({\n path: result.path,\n rendered: result.rendered,\n })\n },\n )\n\n // load\n server.tool(\n verbName(\"load\"),\n description(\"load\", \"Read a manifest from disk. Returns the parsed handle.\"),\n {\n path: z.string().describe(\"Absolute or workspace-relative path to the .md file.\"),\n },\n async ({ path }) => {\n const result = await verbs.load(anchor(path))\n return contentText({ path: result.path, handle: result.handle })\n },\n )\n\n // list\n server.tool(\n verbName(\"list\"),\n description(\n \"list\",\n \"Walk a directory tree and return all manifests of this doctype.\",\n ),\n {\n dir: z.string().describe(\"Directory to walk.\"),\n skipDirs: z\n .array(z.string())\n .optional()\n .describe(\"Subdir names to skip (default: node_modules, .git, dist).\"),\n },\n async ({ dir, skipDirs }) => {\n const handles = await verbs.list(anchor(dir), { skipDirs })\n return contentText({ count: handles.length, handles })\n },\n )\n\n // update\n server.tool(\n verbName(\"update\"),\n description(\n \"update\",\n \"Patch an existing manifest. The patch is shallow-merged into the existing params.\",\n ),\n {\n path: z.string().describe(\"Path to the manifest to update.\"),\n patch: z\n .record(z.string(), z.unknown())\n .describe(\"Partial fields to merge into the existing manifest.\"),\n body: z.string().optional().describe(\"New body markdown (default: keep existing).\"),\n },\n async ({ path, patch, body }) => {\n const result = await verbs.update(\n anchor(path),\n (existing: Record<string, unknown>) => ({ ...existing, ...patch }),\n { body },\n )\n return contentText({ path: result.path, rendered: result.rendered })\n },\n )\n\n // resolve\n server.tool(\n verbName(\"resolve\"),\n description(\n \"resolve\",\n \"Resolve an inline | ref | file block to a fully-typed handle.\",\n ),\n {\n block: z\n .union([\n z.object({ inline: z.record(z.string(), z.unknown()) }),\n z.object({ ref: z.string() }),\n z.object({ file: z.string() }),\n ])\n .describe(\n 'The composition block. Exactly one of: { \"inline\": {...params} } | { \"ref\": \"@scope/id\" } | { \"file\": \"relative/path.md\" }. Omitting the wrapping key causes invalid_union.',\n ),\n baseDir: z\n .string()\n .optional()\n .describe(\"Base dir for `file:` references.\"),\n },\n async ({ block, baseDir }) => {\n const handle = await verbs.resolve(block, {\n baseDir: baseDir ? anchor(baseDir) : undefined,\n })\n return contentText({ handle })\n },\n )\n\n // delete\n server.tool(\n verbName(\"delete\"),\n description(\"delete\", \"Remove a manifest file from disk.\"),\n {\n path: z.string().describe(\"Path to the manifest to delete.\"),\n },\n async ({ path }) => {\n const target = anchor(path)\n await verbs.delete(target)\n return contentText({ deleted: target })\n },\n )\n}\n\n// ── extension loader ────────────────────────────────────────────────\n\nasync function loadExtensions(\n workspace: string,\n specs: readonly AnySpec[],\n): Promise<AnySpec[]> {\n const extDir = resolve(workspace, \"extensions\")\n if (!existsSync(extDir)) return []\n\n const out: AnySpec[] = []\n const { readdir } = await import(\"node:fs/promises\")\n type SimpleDirent = { name: string; isDirectory(): boolean }\n\n let entries: SimpleDirent[]\n try {\n entries = (await readdir(extDir, {\n withFileTypes: true,\n })) as unknown as SimpleDirent[]\n } catch {\n return out\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n const manifestPath = join(extDir, String(entry.name), \"EXTENSION.md\")\n if (!existsSync(manifestPath)) continue\n\n const source = await readFile(manifestPath, \"utf8\")\n const parsed = parseExtensionManifest(source)\n const ext = parsed.frontmatter\n\n let parent: AnySpec | undefined\n if (ext.extends && ext.extends !== \"none\") {\n const aipMatch = ext.extends.match(/^aip-(\\d+)$/)\n if (!aipMatch) {\n throw new Error(\n `mcp-server: extension '${ext.slug}' has invalid extends '${ext.extends}'`,\n )\n }\n const parentAip = Number(aipMatch[1])\n parent = specs.find((s) => s.aip === parentAip)\n if (!parent) {\n throw new Error(\n `mcp-server: extension '${ext.slug}' extends aip-${parentAip}, but no spec for that AIP was registered. Pass the parent spec in opts.specs.`,\n )\n }\n }\n\n out.push(specFromExtension(ext, { parent }) as AnySpec)\n }\n\n return out\n}\n\n// ── tool result helpers ─────────────────────────────────────────────\n\nfunction contentText(payload: unknown): {\n content: Array<{ type: \"text\"; text: string }>\n} {\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(payload, null, 2),\n },\n ],\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/self-inspect-tool.ts","../src/to-mcp-tool.ts","../src/index.ts"],"names":["join","z","contentText"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,eAAsB,gBAAA,CACpB,KACA,SAAA,EACqB;AACrB,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,OAAO,EAAE,EAAA,EAAI,GAAA,EAAK,WAAA,EAAa,0CAAA,EAAsC;AAAA,EACvE;AACA,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,IAAA,EAAM;AAC3C,IAAA,OAAO,EAAE,EAAA,EAAI,MAAA,CAAO,GAAG,CAAA,EAAG,aAAa,qBAAA,EAAsB;AAAA,EAC/D;AACA,EAAA,MAAM,KAAA,GAAQ,GAAA;AACd,EAAA,IAAI,MAAM,IAAA,EAAM;AACd,IAAA,IAAI;AACF,MAAA,MAAM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,GACF;AACF","file":"index.mjs","sourcesContent":["/**\n * self_inspect — MCP tool that lets an agent query its own AIP-42 manifest\n * without knowing its disk path.\n *\n * The agent supplies its logical `id`; the runtime resolves\n * `<workspace>/.agents/<id>/AGENT.md`, loads it via `agentVerbs`, resolves\n * each tool and routine ref to a `{ id, description }` summary, and returns\n * `{ agentPath, tools, routines }`.\n *\n * Injection mechanism: the workspace path is captured in the\n * `registerSelfInspectTool` closure at server-creation time (same pattern as\n * `registerFsTools`). The agent provides its logical id (known from its own\n * system-prompt frontmatter) — not an absolute path.\n */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { z } from \"zod\"\nimport { join } from \"node:path\"\nimport { agentVerbs } from \"@agentproto/agent\"\nimport { toolVerbs } from \"@agentproto/tool\"\nimport { routineVerbs } from \"@agentproto/routine\"\n\nexport interface RefSummary {\n id: string\n description: string\n}\n\nexport interface SelfInspectResult {\n agentPath: string\n tools: RefSummary[]\n routines: RefSummary[]\n}\n\n/**\n * Reduce one AIP-27 ref block (from an agent's `tools[]`) to `{id, description}`.\n *\n * - `file:` → load the TOOL.md and extract `id` + `description` from the handle.\n * `baseDir` is the workspace root (tools live at `<workspace>/tools/<id>/TOOL.md`\n * by the AIP-14 `pathOf` convention, or wherever the file pointer says).\n * - `inline:` → use the inline params directly.\n * - `ref:` or `string` → surface the ref identifier as the id (registry resolution\n * requires an external resolver not available here at inspect time).\n */\nexport async function summarizeToolRef(\n raw: unknown,\n workspace: string,\n): Promise<RefSummary> {\n if (typeof raw === \"string\") {\n return { id: raw, description: \"(string ref — not locally resolved)\" }\n }\n if (typeof raw !== \"object\" || raw === null) {\n return { id: String(raw), description: \"(unknown ref shape)\" }\n }\n const block = raw as { ref?: string; file?: string; inline?: Record<string, unknown> }\n if (block.file) {\n try {\n const handle = await toolVerbs.resolve(\n { file: block.file },\n { baseDir: workspace },\n )\n return { id: handle.id, description: handle.description ?? \"\" }\n } catch {\n return { id: block.file, description: \"(file ref — could not load)\" }\n }\n }\n if (block.inline) {\n return {\n id: String(block.inline.id ?? \"\"),\n description: String(block.inline.description ?? \"\"),\n }\n }\n if (block.ref) {\n return { id: block.ref, description: \"(ref — not locally resolved)\" }\n }\n return { id: JSON.stringify(raw), description: \"(unknown ref shape)\" }\n}\n\n/**\n * Same logic for AIP-41 routine refs. Routines live at\n * `<workspace>/.routines/<id>/ROUTINE.md` by `routineSpec.pathOf` convention.\n */\nexport async function summarizeRoutineRef(\n raw: unknown,\n workspace: string,\n): Promise<RefSummary> {\n if (typeof raw === \"string\") {\n return { id: raw, description: \"(string ref — not locally resolved)\" }\n }\n if (typeof raw !== \"object\" || raw === null) {\n return { id: String(raw), description: \"(unknown ref shape)\" }\n }\n const block = raw as { ref?: string; file?: string; inline?: Record<string, unknown> }\n if (block.file) {\n try {\n const handle = await routineVerbs.resolve(\n { file: block.file },\n { baseDir: workspace },\n )\n return { id: handle.id, description: handle.description ?? \"\" }\n } catch {\n return { id: block.file, description: \"(file ref — could not load)\" }\n }\n }\n if (block.inline) {\n return {\n id: String(block.inline.id ?? \"\"),\n description: String(block.inline.description ?? \"\"),\n }\n }\n if (block.ref) {\n return { id: block.ref, description: \"(ref — not locally resolved)\" }\n }\n return { id: JSON.stringify(raw), description: \"(unknown ref shape)\" }\n}\n\n/**\n * Core logic, extracted for testability.\n * Throws with `{ error, message }` on `agent_not_found`.\n */\nexport async function selfInspect(\n agentId: string,\n workspace: string,\n): Promise<SelfInspectResult> {\n const agentPath = join(workspace, \".agents\", agentId, \"AGENT.md\")\n\n let handle: Awaited<ReturnType<typeof agentVerbs.load>>[\"handle\"]\n try {\n const result = await agentVerbs.load(agentPath)\n handle = result.handle\n } catch (err) {\n const e = new Error(\n `No AGENT.md found for agent '${agentId}' at '${agentPath}'. ` +\n `Ensure an AGENT.md exists at <workspace>/.agents/${agentId}/AGENT.md.`,\n )\n ;(e as NodeJS.ErrnoException).code = \"agent_not_found\"\n throw e\n }\n\n const rawTools = (handle.tools ?? []) as unknown[]\n const rawRoutines = (handle.routines ?? []) as unknown[]\n\n const [tools, routines] = await Promise.all([\n Promise.all(rawTools.map((r) => summarizeToolRef(r, workspace))),\n Promise.all(rawRoutines.map((r) => summarizeRoutineRef(r, workspace))),\n ])\n\n return { agentPath, tools, routines }\n}\n\n/**\n * Register the `self_inspect` MCP tool on `server`.\n *\n * The workspace path is injected at registration time; the agent only needs to\n * supply its logical `id` at call time — not a disk path. This is called from\n * `createMcpServer` whenever a workspace is provided.\n */\nexport function registerSelfInspectTool(\n server: McpServer,\n opts: { workspace: string },\n): void {\n server.tool(\n \"self_inspect\",\n \"Return this agent's AIP-42 manifest summary (tools + routines) without requiring knowledge of disk paths. \" +\n \"Pass the agent's logical `id` (the `id:` field in its AGENT.md frontmatter); the runtime resolves it to \" +\n \"`<workspace>/.agents/<agentId>/AGENT.md`. Returns `{ agentPath, tools, routines }` — each item has at \" +\n \"minimum `{ id, description }`. File refs are loaded; string/ref refs are surfaced as-is.\",\n {\n agentId: z\n .string()\n .min(1)\n .describe(\n \"The agent's logical id (e.g. 'writer'). Matches the `id:` field in the AGENT.md frontmatter. \" +\n \"The runtime resolves this to `<workspace>/.agents/<agentId>/AGENT.md` — \" +\n \"you do not need to know the absolute disk path.\",\n ),\n },\n async ({ agentId }) => {\n try {\n const result = await selfInspect(agentId, opts.workspace)\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(result, null, 2),\n },\n ],\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: \"agent_not_found\", message }, null, 2),\n },\n ],\n isError: true,\n }\n }\n },\n )\n}\n","/**\n * toMcpTool — expose an AIP-14 TOOL contract as a callable MCP tool whose body\n * is `runTool` (resolve DRIVER → validate → execute → validate). The mirror of\n * the Mastra `resolveTool` adapter: one TOOL handle, one resolver, three call\n * surfaces (CLI, agent, MCP) with no per-surface re-coding.\n *\n * Framework-only: it takes a handle + candidate DRIVERs and never knows what\n * the tool does. The injected per-call `context` (live capabilities such as a\n * warm browser session) is baked in at registration by the composition root —\n * an MCP client supplies only the tool's declared input, never context.\n */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { ZodRawShape, ZodType } from \"zod\"\nimport { runTool, type DriverHandle, type ResolverContext } from \"@agentproto/driver\"\nimport type { ToolContext, ToolHandle } from \"@agentproto/tool\"\n\nexport interface ToMcpToolOptions<\n TInput,\n TOutput,\n TContext extends ToolContext,\n> {\n /** The AIP-14 contract to expose. */\n tool: ToolHandle<TInput, TOutput, TContext>\n /** Candidate DRIVERs the resolver dispatches over. */\n candidates: readonly DriverHandle[]\n /**\n * Per-call injected context (live capabilities). A value, or a factory run\n * once per invocation (e.g. to lease a fresh session). Omit for context-free\n * tools (`report.render`).\n */\n context?:\n | TContext\n | (() => TContext | Promise<TContext>)\n /** Resolver routing hints (region, pinned provider, policy tags). */\n resolverContext?: ResolverContext\n /** Resolved secrets to inject into the DriverContext. */\n secrets?: Record<string, string>\n /** Override the advertised MCP tool name (default: tool id, `:`/`.`→`_`). */\n name?: string\n}\n\n/** What `buildMcpTool` produces — registerable on any McpServer, and directly\n * callable in tests without standing up a transport. */\nexport interface McpToolRegistration {\n name: string\n description: string\n inputShape: ZodRawShape\n handler: (args: Record<string, unknown>) => Promise<{\n content: Array<{ type: \"text\"; text: string }>\n }>\n}\n\n/** A ZodObject exposes a `.shape` raw-shape getter; everything else doesn't. */\nfunction asObjectShape(schema: ZodType): ZodRawShape | undefined {\n const shape = (schema as { shape?: unknown }).shape\n return shape && typeof shape === \"object\"\n ? (shape as ZodRawShape)\n : undefined\n}\n\nfunction mcpName(id: string): string {\n return id.replace(/[-:.]/g, \"_\")\n}\n\nfunction contentText(payload: unknown): {\n content: Array<{ type: \"text\"; text: string }>\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload, null, 2) }],\n }\n}\n\n/**\n * Build (but do not register) the MCP tool. When the contract's `inputSchema`\n * is an object schema, its fields become the MCP tool's parameters directly;\n * otherwise the input is taken under a single `input` parameter carrying the\n * whole schema.\n */\nexport function buildMcpTool<TInput, TOutput, TContext extends ToolContext>(\n opts: ToMcpToolOptions<TInput, TOutput, TContext>,\n): McpToolRegistration {\n const { tool, candidates } = opts\n // `inputSchema` is optional (manifest-only tools declare IO via JSON Schema,\n // not a zod schema). Guard against undefined: a zod object → its shape; a\n // non-object zod schema → a single `input` field; no zod schema → no declared\n // MCP params (`{}`).\n const objectShape =\n tool.inputSchema != null ? asObjectShape(tool.inputSchema) : undefined\n const inputShape: ZodRawShape =\n objectShape ?? (tool.inputSchema != null ? { input: tool.inputSchema } : {})\n\n const resolveContext = async (): Promise<unknown> =>\n typeof opts.context === \"function\"\n ? await (opts.context as () => TContext | Promise<TContext>)()\n : opts.context\n\n return {\n name: opts.name ? mcpName(opts.name) : mcpName(tool.id),\n description: tool.description,\n inputShape,\n handler: async (args) => {\n const input = objectShape ? args : (args.input as unknown)\n const context = await resolveContext()\n const output = await runTool({\n tool,\n candidates,\n input,\n context,\n resolverContext: opts.resolverContext,\n secrets: opts.secrets,\n })\n return contentText(output)\n },\n }\n}\n\n/**\n * Register a TOOL contract as a callable MCP tool on `server`, dispatching each\n * call through `runTool`. Returns the registration (handy for diagnostics /\n * tests). Once registered, the tool is callable from any MCP host with no\n * per-host code.\n */\nexport function toMcpTool<TInput, TOutput, TContext extends ToolContext>(\n server: McpServer,\n opts: ToMcpToolOptions<TInput, TOutput, TContext>,\n): McpToolRegistration {\n const reg = buildMcpTool(opts)\n server.tool(reg.name, reg.description, reg.inputShape, reg.handler)\n return reg\n}\n","/**\n * @agentproto/mcp-server — exposes AIP doctype verbs as MCP tools.\n *\n * Hand a list of `DoctypeSpec` instances (one per registered AIP) and\n * optionally a workspace dir; the server registers\n * `create_<name> / load_<name> / list_<name> / update_<name> /\n * resolve_<name> / delete_<name>` for each spec, including AIP-40\n * extensions auto-loaded from `<workspace>/extensions/<slug>/EXTENSION.md`.\n *\n * Two ways to run it:\n * 1. **Embedded** — call `createMcpServer({ specs, workspace })` and\n * attach to your own transport (stdio, websocket, …).\n * 2. **Standalone** — `runStdioServer({ specs, workspace })` wires\n * stdio for you. Useful as a `mcp_servers.<id>` config entry on\n * Claude Desktop / Cursor / any MCP host.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\"\nimport { z } from \"zod\"\nimport { existsSync } from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport { isAbsolute, join, resolve } from \"node:path\"\nimport { createVerbs, type DoctypeSpec } from \"@agentproto/manifest\"\nimport {\n parseExtensionManifest,\n specFromExtension,\n} from \"@agentproto/extension\"\nimport { registerSelfInspectTool } from \"./self-inspect-tool.js\"\n\n// `RegisterableSpec<TParams, THandle>` is just `DoctypeSpec` plus the\n// constraint that callers passing different generics across the array\n// must type-erase via `as unknown as DoctypeSpec<...>` at the boundary.\n// We don't try to express the heterogeneous list in TS — same trick\n// `@agentproto/driver`'s `implementations[]` uses.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnySpec = DoctypeSpec<any, any>\n\nexport interface CreateMcpServerOptions {\n /** Doctype specs registered as MCP tools. One per AIP. */\n specs: readonly AnySpec[]\n /**\n * Optional workspace dir. If provided, the server scans\n * `<workspace>/extensions/` for `EXTENSION.md` files and registers\n * each as a local doctype. The parent of each extension is resolved\n * by matching the extension's `extends:` field (`aip-N`) against\n * `specs.find(s => s.aip === N)` — so the spec list MUST include the\n * parents the extensions reference, else loading throws.\n */\n workspace?: string\n /** Server name advertised over MCP. Default `agentproto-mcp-server`. */\n name?: string\n /** Server version advertised over MCP. Default `0.1.0-alpha`. */\n version?: string\n}\n\nexport interface CreateMcpServerResult {\n /** The wired McpServer; attach a transport to start serving. */\n server: McpServer\n /**\n * The list of doctype names the server registered tools for —\n * useful for tests + diagnostics. Includes any extensions loaded\n * from `workspace/extensions/`.\n */\n registered: readonly string[]\n}\n\nexport async function createMcpServer(\n opts: CreateMcpServerOptions,\n): Promise<CreateMcpServerResult> {\n const server = new McpServer({\n name: opts.name ?? \"agentproto-mcp-server\",\n version: opts.version ?? \"0.1.0-alpha\",\n })\n\n const allSpecs: AnySpec[] = [...opts.specs]\n\n // Load extensions when a workspace is given.\n if (opts.workspace) {\n const extensions = await loadExtensions(opts.workspace, opts.specs)\n allSpecs.push(...extensions)\n }\n\n // Path-anchoring: when a workspace is set, resolve all relative\n // dir/path arguments against it. Agents pass logical paths like\n // \"tools\" or \"tools/echo/TOOL.md\"; the server pins them to the\n // workspace so they don't leak into process.cwd() (which is\n // wherever the host happened to spawn the server).\n const anchor = (p: string): string =>\n isAbsolute(p) || !opts.workspace ? p : join(opts.workspace, p)\n\n for (const spec of allSpecs) {\n registerVerbs(server, spec, anchor)\n }\n\n // self_inspect: contextual tool injected when a workspace is provided so\n // agents can query their own AIP-42 manifest by logical id — no disk path\n // knowledge required.\n if (opts.workspace) {\n registerSelfInspectTool(server, { workspace: opts.workspace })\n }\n\n return {\n server,\n registered: allSpecs.map((s) => s.name),\n }\n}\n\n/**\n * Wire `createMcpServer` to stdio for use as an `mcp_servers.<id>`\n * entry on Claude Desktop / Cursor / etc. Resolves once the\n * transport closes.\n */\nexport async function runStdioServer(\n opts: CreateMcpServerOptions,\n): Promise<void> {\n const { server } = await createMcpServer(opts)\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nexport {\n toMcpTool,\n buildMcpTool,\n type ToMcpToolOptions,\n type McpToolRegistration,\n} from \"./to-mcp-tool.js\"\nexport {\n registerSelfInspectTool,\n selfInspect,\n summarizeToolRef,\n summarizeRoutineRef,\n type RefSummary,\n type SelfInspectResult,\n} from \"./self-inspect-tool.js\"\n\n// ── verb registration ───────────────────────────────────────────────\n\nfunction registerVerbs(\n server: McpServer,\n spec: AnySpec,\n anchor: (p: string) => string,\n): void {\n const verbs = createVerbs(spec)\n // Tool name uses snake_case to match MCP convention; spec.name may\n // be kebab (driver-cli) or namespaced (acme:deal). Map all to snake.\n const verbName = (verb: string) =>\n `${verb}_${spec.name.replace(/[-:]/g, \"_\")}`\n const description = (verb: string, body: string) =>\n `${verb} the AIP-${spec.aip} ${spec.name} doctype. ${body}`\n\n // create\n server.tool(\n verbName(\"create\"),\n description(\n \"create\",\n \"Author a new manifest from params. Returns { path, rendered }.\",\n ),\n {\n params: z\n .record(z.string(), z.unknown())\n .describe(`The ${spec.name} definition fields.`),\n dir: z.string().describe(\"Workspace-relative or absolute target directory.\"),\n body: z\n .string()\n .optional()\n .describe(\"Markdown body after the frontmatter. Defaults to a stub.\"),\n dryRun: z\n .boolean()\n .optional()\n .describe(\"Render only — don't write to disk.\"),\n },\n async ({ params, dir, body, dryRun }) => {\n const result = await verbs.create(params, {\n dir: anchor(dir),\n body,\n dryRun,\n })\n return contentText({\n path: result.path,\n rendered: result.rendered,\n })\n },\n )\n\n // load\n server.tool(\n verbName(\"load\"),\n description(\"load\", \"Read a manifest from disk. Returns the parsed handle.\"),\n {\n path: z.string().describe(\"Absolute or workspace-relative path to the .md file.\"),\n },\n async ({ path }) => {\n const result = await verbs.load(anchor(path))\n return contentText({ path: result.path, handle: result.handle })\n },\n )\n\n // list\n server.tool(\n verbName(\"list\"),\n description(\n \"list\",\n \"Walk a directory tree and return all manifests of this doctype.\",\n ),\n {\n dir: z.string().describe(\"Directory to walk.\"),\n skipDirs: z\n .array(z.string())\n .optional()\n .describe(\"Subdir names to skip (default: node_modules, .git, dist).\"),\n },\n async ({ dir, skipDirs }) => {\n const handles = await verbs.list(anchor(dir), { skipDirs })\n return contentText({ count: handles.length, handles })\n },\n )\n\n // update\n server.tool(\n verbName(\"update\"),\n description(\n \"update\",\n \"Patch an existing manifest. The patch is shallow-merged into the existing params.\",\n ),\n {\n path: z.string().describe(\"Path to the manifest to update.\"),\n patch: z\n .record(z.string(), z.unknown())\n .describe(\"Partial fields to merge into the existing manifest.\"),\n body: z.string().optional().describe(\"New body markdown (default: keep existing).\"),\n },\n async ({ path, patch, body }) => {\n const result = await verbs.update(\n anchor(path),\n (existing: Record<string, unknown>) => ({ ...existing, ...patch }),\n { body },\n )\n return contentText({ path: result.path, rendered: result.rendered })\n },\n )\n\n // resolve\n server.tool(\n verbName(\"resolve\"),\n description(\n \"resolve\",\n \"Resolve an inline | ref | file block to a fully-typed handle.\",\n ),\n {\n block: z\n .union([\n z.object({ inline: z.record(z.string(), z.unknown()) }),\n z.object({ ref: z.string() }),\n z.object({ file: z.string() }),\n ])\n .describe(\n 'The composition block. Exactly one of: { \"inline\": {...params} } | { \"ref\": \"@scope/id\" } | { \"file\": \"relative/path.md\" }. Omitting the wrapping key causes invalid_union.',\n ),\n baseDir: z\n .string()\n .optional()\n .describe(\"Base dir for `file:` references.\"),\n },\n async ({ block, baseDir }) => {\n const handle = await verbs.resolve(block, {\n baseDir: baseDir ? anchor(baseDir) : undefined,\n })\n return contentText({ handle })\n },\n )\n\n // delete\n server.tool(\n verbName(\"delete\"),\n description(\"delete\", \"Remove a manifest file from disk.\"),\n {\n path: z.string().describe(\"Path to the manifest to delete.\"),\n },\n async ({ path }) => {\n const target = anchor(path)\n await verbs.delete(target)\n return contentText({ deleted: target })\n },\n )\n}\n\n// ── extension loader ────────────────────────────────────────────────\n\nasync function loadExtensions(\n workspace: string,\n specs: readonly AnySpec[],\n): Promise<AnySpec[]> {\n const extDir = resolve(workspace, \"extensions\")\n if (!existsSync(extDir)) return []\n\n const out: AnySpec[] = []\n const { readdir } = await import(\"node:fs/promises\")\n type SimpleDirent = { name: string; isDirectory(): boolean }\n\n let entries: SimpleDirent[]\n try {\n entries = (await readdir(extDir, {\n withFileTypes: true,\n })) as unknown as SimpleDirent[]\n } catch {\n return out\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n const manifestPath = join(extDir, String(entry.name), \"EXTENSION.md\")\n if (!existsSync(manifestPath)) continue\n\n const source = await readFile(manifestPath, \"utf8\")\n const parsed = parseExtensionManifest(source)\n const ext = parsed.frontmatter\n\n let parent: AnySpec | undefined\n if (ext.extends && ext.extends !== \"none\") {\n const aipMatch = ext.extends.match(/^aip-(\\d+)$/)\n if (!aipMatch) {\n throw new Error(\n `mcp-server: extension '${ext.slug}' has invalid extends '${ext.extends}'`,\n )\n }\n const parentAip = Number(aipMatch[1])\n parent = specs.find((s) => s.aip === parentAip)\n if (!parent) {\n throw new Error(\n `mcp-server: extension '${ext.slug}' extends aip-${parentAip}, but no spec for that AIP was registered. Pass the parent spec in opts.specs.`,\n )\n }\n }\n\n out.push(specFromExtension(ext, { parent }) as AnySpec)\n }\n\n return out\n}\n\n// ── tool result helpers ─────────────────────────────────────────────\n\nfunction contentText(payload: unknown): {\n content: Array<{ type: \"text\"; text: string }>\n} {\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(payload, null, 2),\n },\n ],\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/mcp-server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "@agentproto/mcp-server — exposes every AIP doctype as MCP tools. Pass DoctypeSpec instances + an optional workspace dir for EXTENSION.md auto-loading; the server registers create_X / load_X / list_X / update_X / resolve_X / delete_X for each registered doctype, including AIP-40 extensions. Compose to build agent runtimes that author and edit AIP manifests over MCP.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"bugs": {
|
|
20
20
|
"url": "https://github.com/agentproto/ts/issues"
|
|
21
21
|
},
|
|
22
|
-
"license": "
|
|
22
|
+
"license": "Apache-2.0",
|
|
23
23
|
"type": "module",
|
|
24
24
|
"main": "dist/index.mjs",
|
|
25
25
|
"module": "dist/index.mjs",
|
|
@@ -43,13 +43,13 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
45
45
|
"zod": "^4.4.3",
|
|
46
|
-
"@agentproto/agent": "0.2.
|
|
47
|
-
"@agentproto/define-doctype": "0.1.
|
|
48
|
-
"@agentproto/driver": "0.1.
|
|
49
|
-
"@agentproto/extension": "0.1.
|
|
50
|
-
"@agentproto/manifest": "0.2.
|
|
51
|
-
"@agentproto/routine": "0.1.
|
|
52
|
-
"@agentproto/tool": "0.
|
|
46
|
+
"@agentproto/agent": "0.2.1",
|
|
47
|
+
"@agentproto/define-doctype": "0.1.1",
|
|
48
|
+
"@agentproto/driver": "0.1.3",
|
|
49
|
+
"@agentproto/extension": "0.1.2",
|
|
50
|
+
"@agentproto/manifest": "0.2.1",
|
|
51
|
+
"@agentproto/routine": "0.1.2",
|
|
52
|
+
"@agentproto/tool": "0.2.1"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/node": "^25.6.2",
|