@glyphp/adapter-mcp-server 1.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,202 @@
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/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # @glyphp/adapter-mcp-server
2
+
3
+ > Expose a [Glyph Protocol](https://github.com/Monoperro0207/glyph-protocol) server's tools to any [Model Context Protocol](https://modelcontextprotocol.io) client (Claude Desktop, Hermes Agent, Cursor, etc.).
4
+
5
+ This is the **inverse direction** of `@glyphp/adapter-mcp` (which adapts MCP tools *into* Glyph). Together they let the two ecosystems consume each other.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @glyphp/adapter-mcp-server @glyphp/client
11
+ ```
12
+
13
+ ## Use
14
+
15
+ ```ts
16
+ import { GlyphClient } from '@glyphp/client'
17
+ import { runStdioBridge } from '@glyphp/adapter-mcp-server'
18
+
19
+ const client = new GlyphClient({ baseUrl: 'http://localhost:3199' })
20
+ await runStdioBridge(client) // MCP stdio server now serving Glyph tools
21
+ ```
22
+
23
+ Point any MCP client at the resulting process — `claude_desktop_config.json`, Hermes Agent's `mcp_servers` block, Cursor's MCP setting — and the Glyph server's tools appear as native MCP tools.
24
+
25
+ ## Two modes: eager vs lazy
26
+
27
+ The example above uses **eager mode** — every Glyph card is surfaced as its own MCP tool. Simple, works with any MCP client, but every `tools/list` carries every schema.
28
+
29
+ For large catalogs (dozens of tools), use **lazy mode**. It exposes only three meta-tools — `glyph_index`, `glyph_describe`, `glyph_invoke` — and lets the model navigate on demand. Cards the agent never touches never enter context.
30
+
31
+ ```ts
32
+ import { runStdioBridgeLazy } from '@glyphp/adapter-mcp-server'
33
+ await runStdioBridgeLazy(client)
34
+ ```
35
+
36
+ Measured trade-off (`spec/tests/hermes-comparative-deepseek.md` — same prompt, same 49 tools, `deepseek-v4-pro`):
37
+
38
+ | Metric | Eager | Lazy | Δ |
39
+ |---:|---:|---:|---:|
40
+ | Tools visible in `tools/list` | 49 | 3 | — |
41
+ | Listing tokens (per turn) | 4,129 | 256 | **−93.8%** |
42
+ | Total tokens (full task) | 168,971 | 77,576 | **−54.1%** |
43
+ | Cost (DeepSeek rates) | $0.0227 | $0.0137 | −40% |
44
+
45
+ The honest catch: lazy mode pays two extra round-trips at the start of a session for discovery. For very small catalogs (<10 tools) or one-shot tasks, eager is preferable. The two modes are exported side-by-side — pick the right one for your shape of problem.
46
+
47
+ ## Honest mapping
48
+
49
+ MCP and Glyph are not isomorphic. The bridge preserves what MCP can carry and consumes the rest server-side:
50
+
51
+ | Glyph concept | What the bridge does |
52
+ |---|---|
53
+ | `card.name` | Becomes the MCP tool name |
54
+ | `card.intent` | Becomes the MCP tool description |
55
+ | `card.cost.riskTier` / `sideEffects` / `reversible` | Surfaced **in the description** so the model can reason about blast radius before invoking |
56
+ | `card.input` schema | Passed through verbatim as MCP `inputSchema` |
57
+ | `card.publicKey` / `signature` | Verified by `GlyphClient` server-side — **not exposed to MCP** (MCP has nowhere to put them) |
58
+ | `cost.requiresConfirmation: true` | Refused at the bridge with a clear error — the MCP transport has no ticket/confirmation flow, and auto-confirming would defeat the gate |
59
+ | `SealedEnvelope.receipt` | Verified server-side, then **dropped** — MCP has no signed-receipt concept |
60
+ | `SealedEnvelope.inspection` | When sanitization removed content, a short annotation is appended to the MCP response text so the consuming model knows defense ran |
61
+ | `card.attestation` | **Not exposed.** A consumer that needs to verify attestations should speak Glyph natively |
62
+
63
+ If your use case requires the cryptographic guarantees (signed receipts for audit, attestation verification, pinning gates), use `@glyphp/client` directly. The bridge is for **integration with the MCP ecosystem**, not for security-critical paths.
64
+
65
+ ## License
66
+
67
+ Apache-2.0
@@ -0,0 +1,31 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import type { GlyphClient } from '@glyphp/client';
3
+ export interface BridgeOptions {
4
+ /** Reported as the MCP server name on handshake. */
5
+ serverName?: string;
6
+ /** Reported as the MCP server version on handshake. */
7
+ serverVersion?: string;
8
+ /**
9
+ * When false, the bridge fetches the lexicon on every `tools/list` call.
10
+ * When true (default), it caches per session for speed. Cache lives for
11
+ * the lifetime of the bridge process; restart to pick up new tools.
12
+ */
13
+ cacheLexicon?: boolean;
14
+ }
15
+ /**
16
+ * Builds an MCP Server that exposes a Glyph server's tools. Wire it up with
17
+ * any transport — stdio is most common.
18
+ *
19
+ * @example
20
+ * const client = new GlyphClient({ baseUrl: 'http://localhost:3199' })
21
+ * const server = mcpServerFromGlyph(client)
22
+ * await server.connect(new StdioServerTransport())
23
+ */
24
+ export declare function mcpServerFromGlyph(client: GlyphClient, options?: BridgeOptions): Server;
25
+ /**
26
+ * Convenience: builds the bridge and connects it over stdio. Useful for a
27
+ * one-line bin script. Resolves once the transport is wired.
28
+ */
29
+ export declare function runStdioBridge(client: GlyphClient, options?: BridgeOptions): Promise<Server>;
30
+ export { mcpServerFromGlyphLazy, runStdioBridgeLazy, type LazyBridgeOptions, } from './lazy.js';
31
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAwCA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAA;AAElE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAGjD,MAAM,WAAW,aAAa;IAC5B,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,uDAAuD;IACvD,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,aAAkB,GAC1B,MAAM,CA8GR;AAyDD;;;GAGG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,WAAW,EACnB,OAAO,CAAC,EAAE,aAAa,GACtB,OAAO,CAAC,MAAM,CAAC,CAIjB;AAED,OAAO,EACL,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,iBAAiB,GACvB,MAAM,WAAW,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,206 @@
1
+ /**
2
+ * @glyphp/adapter-mcp-server — expose a Glyph Protocol server's tools to any
3
+ * MCP client.
4
+ *
5
+ * Two modes:
6
+ * - **Eager** (this file): every Glyph card surfaced as an MCP tool. Simple,
7
+ * works with any MCP client, but every `tools/list` carries every schema.
8
+ * - **Lazy** (`./lazy.ts`): only three meta-tools (`glyph_index`,
9
+ * `glyph_describe`, `glyph_invoke`). The model navigates on demand.
10
+ * Tokens spent on tool descriptions drop ~80-95% on multi-tool servers.
11
+ *
12
+ * This is the inverse direction of `@glyphp/adapter-mcp`. Together they let
13
+ * Glyph and MCP ecosystems consume each other.
14
+ *
15
+ * ## Honest mapping notes
16
+ *
17
+ * MCP and Glyph are not isomorphic. The bridge preserves what MCP can carry
18
+ * and consumes the rest server-side:
19
+ *
20
+ * - **Preserved**: tool name, intent (as description), input schema, output
21
+ * payload, risk-tier as a description annotation.
22
+ * - **Surfaced as MCP isError**: confirmation gate refusals (when a Glyph
23
+ * tool declares `requiresConfirmation`, the bridge cannot satisfy the
24
+ * ticket flow for an MCP client that has no ticket concept — the call is
25
+ * refused with a clear error).
26
+ * - **Consumed server-side**: card signatures (verified by GlyphClient),
27
+ * receipt signatures (verified by GlyphClient), the SealedEnvelope's
28
+ * `inspection` report — when it removed anything, a brief note is appended
29
+ * to the MCP content so the calling model sees that sanitization happened.
30
+ * - **Lost**: the cryptographic receipt itself, the publicKey, the
31
+ * attestation envelope. MCP has nowhere to put them. This is the
32
+ * structural reason a security-conscious consumer should speak Glyph
33
+ * natively rather than through this bridge.
34
+ *
35
+ * See `spec/tests/hermes-deepseek.md` for a worked example.
36
+ */
37
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
38
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
39
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
40
+ /**
41
+ * Builds an MCP Server that exposes a Glyph server's tools. Wire it up with
42
+ * any transport — stdio is most common.
43
+ *
44
+ * @example
45
+ * const client = new GlyphClient({ baseUrl: 'http://localhost:3199' })
46
+ * const server = mcpServerFromGlyph(client)
47
+ * await server.connect(new StdioServerTransport())
48
+ */
49
+ export function mcpServerFromGlyph(client, options = {}) {
50
+ const server = new Server({
51
+ name: options.serverName ?? 'glyph-mcp-bridge',
52
+ version: options.serverVersion ?? '0.1.0',
53
+ }, { capabilities: { tools: {} } });
54
+ /**
55
+ * MCP tool names match OpenAI's restriction: `^[a-zA-Z0-9_-]+$`. Glyph
56
+ * allows richer names (dots, slashes) — `fs.read`, `db/query`, etc. We
57
+ * translate by replacing every disallowed character with `_` and keep a
58
+ * reverse map so `tools/call` can find the original card. Collisions are
59
+ * caught at registration time (two glyph names that normalize to the same
60
+ * MCP name throw).
61
+ */
62
+ let cardCache;
63
+ /** mcp-safe-name → original card.name */
64
+ let nameAlias;
65
+ const sanitizeMcpName = (name) => name.replace(/[^a-zA-Z0-9_-]/g, '_');
66
+ const loadCards = async () => {
67
+ if (cardCache && nameAlias && options.cacheLexicon !== false) {
68
+ return { cards: cardCache, alias: nameAlias };
69
+ }
70
+ const lexicon = await client.getLexicon();
71
+ const cards = new Map();
72
+ const alias = new Map();
73
+ for (const entry of lexicon) {
74
+ const card = await client.getCard(entry.name, 'rich');
75
+ cards.set(entry.name, card);
76
+ const safe = sanitizeMcpName(entry.name);
77
+ if (alias.has(safe)) {
78
+ throw new Error(`MCP name collision: glyph "${entry.name}" and "${alias.get(safe)}" both normalize to "${safe}". Rename one.`);
79
+ }
80
+ alias.set(safe, entry.name);
81
+ }
82
+ cardCache = cards;
83
+ nameAlias = alias;
84
+ return { cards, alias };
85
+ };
86
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
87
+ const { cards } = await loadCards();
88
+ return {
89
+ tools: Array.from(cards.values()).map((card) => ({
90
+ name: sanitizeMcpName(card.name),
91
+ description: describeForMcp(card),
92
+ inputSchema: card.input ?? {
93
+ type: 'object',
94
+ },
95
+ })),
96
+ };
97
+ });
98
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
99
+ const { name, arguments: args } = req.params;
100
+ const { cards, alias } = await loadCards();
101
+ // Accept either the MCP-safe name (what the model saw) or the original
102
+ // glyph name. Most clients echo the listed name verbatim.
103
+ const originalName = alias.get(name) ?? name;
104
+ const card = cards.get(originalName);
105
+ if (!card) {
106
+ return {
107
+ isError: true,
108
+ content: [{ type: 'text', text: `Unknown Glyph tool: ${name}` }],
109
+ };
110
+ }
111
+ // Glyph's confirmation gate has no MCP equivalent. Refusing here surfaces
112
+ // the requirement to the model rather than silently approving — which
113
+ // would defeat the gate's purpose.
114
+ if (card.cost.requiresConfirmation) {
115
+ return {
116
+ isError: true,
117
+ content: [
118
+ {
119
+ type: 'text',
120
+ text: `Glyph tool "${name}" requires confirmation. The MCP bridge cannot satisfy this flow — call this tool via a native Glyph client that supports the prepare/confirm handshake.`,
121
+ },
122
+ ],
123
+ };
124
+ }
125
+ try {
126
+ const envelope = (await client.call(originalName, (args ?? {})));
127
+ return envelopeToMcpResult(envelope);
128
+ }
129
+ catch (err) {
130
+ return {
131
+ isError: true,
132
+ content: [
133
+ {
134
+ type: 'text',
135
+ text: `Glyph call failed: ${err instanceof Error ? err.message : String(err)}`,
136
+ },
137
+ ],
138
+ };
139
+ }
140
+ });
141
+ return server;
142
+ }
143
+ /**
144
+ * Builds the MCP `description` string the model sees. We surface the risk
145
+ * tier and confirmation flag in plain language so the model can reason about
146
+ * blast radius before invoking — matching the spirit of MCP's annotations
147
+ * but with the explicit Glyph vocabulary preserved.
148
+ */
149
+ function describeForMcp(card) {
150
+ const tags = [];
151
+ if (card.cost.riskTier !== 'safe') {
152
+ tags.push(`risk: ${card.cost.riskTier}`);
153
+ }
154
+ if (card.cost.sideEffects)
155
+ tags.push('has side effects');
156
+ if (!card.cost.reversible)
157
+ tags.push('not reversible');
158
+ if (card.cost.requiresConfirmation)
159
+ tags.push('requires confirmation');
160
+ const suffix = tags.length > 0 ? ` (${tags.join(', ')})` : '';
161
+ return `${card.intent}${suffix}`;
162
+ }
163
+ /**
164
+ * Maps a SealedEnvelope to an MCP CallToolResult. We:
165
+ * - Encode the payload as a single text content block (JSON-stringified).
166
+ * - If sanitization removed anything, append a brief annotation so the
167
+ * model sees that Glyph defended against invisible content — this is the
168
+ * only place the bridge surfaces the security work it did.
169
+ */
170
+ function envelopeToMcpResult(envelope) {
171
+ const blocks = [
172
+ {
173
+ type: 'text',
174
+ text: typeof envelope.payload === 'string'
175
+ ? envelope.payload
176
+ : JSON.stringify(envelope.payload, null, 2),
177
+ },
178
+ ];
179
+ const inspection = envelope.inspection;
180
+ if (inspection && inspection.findings.length > 0) {
181
+ const counts = new Map();
182
+ for (const f of inspection.findings) {
183
+ counts.set(f.kind, (counts.get(f.kind) ?? 0) + f.count);
184
+ }
185
+ const breakdown = Array.from(counts.entries())
186
+ .map(([kind, count]) => `${count} ${kind}`)
187
+ .join(', ');
188
+ const total = Array.from(counts.values()).reduce((a, b) => a + b, 0);
189
+ blocks.push({
190
+ type: 'text',
191
+ text: `[glyph: sanitized ${total} invisible character(s) from this output — ${breakdown}]`,
192
+ });
193
+ }
194
+ return { content: blocks };
195
+ }
196
+ /**
197
+ * Convenience: builds the bridge and connects it over stdio. Useful for a
198
+ * one-line bin script. Resolves once the transport is wired.
199
+ */
200
+ export async function runStdioBridge(client, options) {
201
+ const server = mcpServerFromGlyph(client, options);
202
+ await server.connect(new StdioServerTransport());
203
+ return server;
204
+ }
205
+ export { mcpServerFromGlyphLazy, runStdioBridgeLazy, } from './lazy.js';
206
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":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dk/server/index.js';
2
+ import type { GlyphClient } from '@glyphp/client';
3
+ export interface LazyBridgeOptions {
4
+ serverName?: string;
5
+ serverVersion?: string;
6
+ }
7
+ export declare function mcpServerFromGlyphLazy(client: GlyphClient, options?: LazyBridgeOptions): Server;
8
+ export declare function runStdioBridgeLazy(client: GlyphClient, options?: LazyBridgeOptions): Promise<Server>;
9
+ //# sourceMappingURL=lazy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lazy.d.ts","sourceRoot":"","sources":["../src/lazy.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAA;AAElE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAGjD,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAkCD,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE,iBAAsB,GAC9B,MAAM,CA6FR;AAuCD,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,WAAW,EACnB,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,MAAM,CAAC,CAIjB"}
package/dist/lazy.js ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Lazy bridge mode — Glyph's actual cost-saving philosophy.
3
+ *
4
+ * Where the eager bridge (in `index.ts`) dumps every card's schema into
5
+ * `tools/list` (so a 50-tool server costs ~12k tokens per turn), the lazy
6
+ * bridge exposes **only three meta-tools** to MCP:
7
+ *
8
+ * 1. `glyph_index` → cheap directory: [{name, oneLineIntent, riskTier}]
9
+ * 2. `glyph_describe` → full card for a single tool (schema, cost, etc.)
10
+ * 3. `glyph_invoke` → run the underlying glyph
11
+ *
12
+ * The model navigates: list cheap → describe what it needs → invoke. Cards
13
+ * the agent never touches never enter context. For a 50-tool server on a
14
+ * 10-turn task that touches ~6 tools, this is typically an 80-95% reduction
15
+ * in tokens spent on tool descriptions vs eager MCP, at the cost of 2 extra
16
+ * round-trips per "new" tool the agent decides to use.
17
+ *
18
+ * Trade-off (honest): smaller models may stumble. They have to "discover"
19
+ * tools rather than see them all at once. If your model can't handle that,
20
+ * use eager mode. Test, don't assume.
21
+ */
22
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
23
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
24
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
25
+ const META_TOOLS = [
26
+ {
27
+ name: 'glyph_index',
28
+ description: 'List all available Glyph tools as {name, intent, riskTier}. Cheap — call this first to see what is available, then call glyph_describe for any tool you want to use.',
29
+ inputSchema: { type: 'object', properties: {} },
30
+ },
31
+ {
32
+ name: 'glyph_describe',
33
+ description: 'Get the full card for a single Glyph tool: input schema, output shape, side effects, reversibility, risk. Call this before glyph_invoke so you know what arguments to pass.',
34
+ inputSchema: {
35
+ type: 'object',
36
+ properties: { name: { type: 'string' } },
37
+ required: ['name'],
38
+ },
39
+ },
40
+ {
41
+ name: 'glyph_invoke',
42
+ description: 'Invoke a Glyph tool by name with arguments. The arguments object must match the inputSchema you saw from glyph_describe. Returns the tool output.',
43
+ inputSchema: {
44
+ type: 'object',
45
+ properties: {
46
+ name: { type: 'string' },
47
+ arguments: { type: 'object' },
48
+ },
49
+ required: ['name', 'arguments'],
50
+ },
51
+ },
52
+ ];
53
+ export function mcpServerFromGlyphLazy(client, options = {}) {
54
+ const server = new Server({
55
+ name: options.serverName ?? 'glyph-mcp-bridge-lazy',
56
+ version: options.serverVersion ?? '0.1.0',
57
+ }, { capabilities: { tools: {} } });
58
+ // Card cache so describe/invoke don't re-fetch.
59
+ const cards = new Map();
60
+ let indexLoaded = false;
61
+ async function ensureIndex() {
62
+ if (indexLoaded)
63
+ return;
64
+ const lexicon = await client.getLexicon();
65
+ for (const entry of lexicon) {
66
+ const card = await client.getCard(entry.name, 'rich');
67
+ cards.set(entry.name, card);
68
+ }
69
+ indexLoaded = true;
70
+ }
71
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
72
+ tools: META_TOOLS,
73
+ }));
74
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
75
+ const { name, arguments: args } = req.params;
76
+ try {
77
+ if (name === 'glyph_index') {
78
+ await ensureIndex();
79
+ const entries = Array.from(cards.values()).map((c) => ({
80
+ name: c.name,
81
+ intent: c.intent,
82
+ riskTier: c.cost.riskTier,
83
+ }));
84
+ return {
85
+ content: [{ type: 'text', text: JSON.stringify(entries) }],
86
+ };
87
+ }
88
+ if (name === 'glyph_describe') {
89
+ await ensureIndex();
90
+ const target = args?.name;
91
+ if (!target) {
92
+ return errorResult('glyph_describe requires {name}');
93
+ }
94
+ const card = cards.get(target);
95
+ if (!card)
96
+ return errorResult(`unknown glyph: ${target}`);
97
+ return {
98
+ content: [
99
+ {
100
+ type: 'text',
101
+ text: JSON.stringify({
102
+ name: card.name,
103
+ intent: card.intent,
104
+ input: card.input,
105
+ output: card.output,
106
+ cost: card.cost,
107
+ }),
108
+ },
109
+ ],
110
+ };
111
+ }
112
+ if (name === 'glyph_invoke') {
113
+ await ensureIndex();
114
+ const p = (args ?? {});
115
+ if (!p.name)
116
+ return errorResult('glyph_invoke requires {name}');
117
+ const card = cards.get(p.name);
118
+ if (!card)
119
+ return errorResult(`unknown glyph: ${p.name}`);
120
+ if (card.cost.requiresConfirmation) {
121
+ return errorResult(`glyph "${p.name}" requires confirmation; not supported via MCP bridge`);
122
+ }
123
+ const envelope = (await client.call(p.name, p.arguments ?? {}));
124
+ return envelopeToMcpResult(envelope);
125
+ }
126
+ return errorResult(`unknown meta-tool: ${name}`);
127
+ }
128
+ catch (err) {
129
+ return errorResult(`lazy bridge error: ${err instanceof Error ? err.message : String(err)}`);
130
+ }
131
+ });
132
+ return server;
133
+ }
134
+ function errorResult(msg) {
135
+ return { isError: true, content: [{ type: 'text', text: msg }] };
136
+ }
137
+ function envelopeToMcpResult(envelope) {
138
+ const blocks = [
139
+ {
140
+ type: 'text',
141
+ text: typeof envelope.payload === 'string'
142
+ ? envelope.payload
143
+ : JSON.stringify(envelope.payload),
144
+ },
145
+ ];
146
+ const inspection = envelope.inspection;
147
+ if (inspection && inspection.findings.length > 0) {
148
+ const counts = new Map();
149
+ for (const f of inspection.findings) {
150
+ counts.set(f.kind, (counts.get(f.kind) ?? 0) + f.count);
151
+ }
152
+ const breakdown = Array.from(counts.entries())
153
+ .map(([k, n]) => `${n} ${k}`)
154
+ .join(', ');
155
+ const total = Array.from(counts.values()).reduce((a, b) => a + b, 0);
156
+ blocks.push({
157
+ type: 'text',
158
+ text: `[glyph: sanitized ${total} invisible character(s) — ${breakdown}]`,
159
+ });
160
+ }
161
+ return { content: blocks };
162
+ }
163
+ export async function runStdioBridgeLazy(client, options) {
164
+ const server = mcpServerFromGlyphLazy(client, options);
165
+ await server.connect(new StdioServerTransport());
166
+ return server;
167
+ }
168
+ //# sourceMappingURL=lazy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lazy.js","sourceRoot":"","sources":["../src/lazy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,oCAAoC,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAA;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAA;AAShF,MAAM,UAAU,GAAG;IACjB;QACE,IAAI,EAAE,aAAa;QACnB,WAAW,EACT,sKAAsK;QACxK,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,EAAE;KAChD;IACD;QACE,IAAI,EAAE,gBAAgB;QACtB,WAAW,EACT,6KAA6K;QAC/K,WAAW,EAAE;YACX,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ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C,CAAC,CAAA;QACpE,MAAM,CAAC,IAAI,CAAC;YACV,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,qBAAqB,KAAK,6BAA6B,SAAS,GAAG;SAC1E,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,CAAA;AAC5B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,MAAmB,EACnB,OAA2B;IAE3B,MAAM,MAAM,GAAG,sBAAsB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACtD,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAA;IAChD,OAAO,MAAM,CAAA;AACf,CAAC"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@glyphp/adapter-mcp-server",
3
+ "version": "1.0.0",
4
+ "description": "Expose a Glyph Protocol server's tools to any MCP client (Claude Desktop, Hermes Agent, Cursor, etc.)",
5
+ "license": "Apache-2.0",
6
+ "author": "Patrick Espino",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Monoperro0207/glyph-protocol.git",
25
+ "directory": "packages/adapters/mcp-server"
26
+ },
27
+ "homepage": "https://github.com/Monoperro0207/glyph-protocol#readme",
28
+ "bugs": "https://github.com/Monoperro0207/glyph-protocol/issues",
29
+ "keywords": [
30
+ "glyph",
31
+ "glyph-protocol",
32
+ "mcp",
33
+ "bridge",
34
+ "adapter"
35
+ ],
36
+ "engines": {
37
+ "node": ">=18"
38
+ },
39
+ "dependencies": {
40
+ "@modelcontextprotocol/sdk": "^1.0.0",
41
+ "@glyphp/client": "1.0.0",
42
+ "@glyphp/types": "1.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "zod": "^3.23.8",
46
+ "@glyphp/server": "1.0.0"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc -p tsconfig.build.json"
50
+ },
51
+ "types": "./dist/index.d.ts"
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1,255 @@
1
+ /**
2
+ * @glyphp/adapter-mcp-server — expose a Glyph Protocol server's tools to any
3
+ * MCP client.
4
+ *
5
+ * Two modes:
6
+ * - **Eager** (this file): every Glyph card surfaced as an MCP tool. Simple,
7
+ * works with any MCP client, but every `tools/list` carries every schema.
8
+ * - **Lazy** (`./lazy.ts`): only three meta-tools (`glyph_index`,
9
+ * `glyph_describe`, `glyph_invoke`). The model navigates on demand.
10
+ * Tokens spent on tool descriptions drop ~80-95% on multi-tool servers.
11
+ *
12
+ * This is the inverse direction of `@glyphp/adapter-mcp`. Together they let
13
+ * Glyph and MCP ecosystems consume each other.
14
+ *
15
+ * ## Honest mapping notes
16
+ *
17
+ * MCP and Glyph are not isomorphic. The bridge preserves what MCP can carry
18
+ * and consumes the rest server-side:
19
+ *
20
+ * - **Preserved**: tool name, intent (as description), input schema, output
21
+ * payload, risk-tier as a description annotation.
22
+ * - **Surfaced as MCP isError**: confirmation gate refusals (when a Glyph
23
+ * tool declares `requiresConfirmation`, the bridge cannot satisfy the
24
+ * ticket flow for an MCP client that has no ticket concept — the call is
25
+ * refused with a clear error).
26
+ * - **Consumed server-side**: card signatures (verified by GlyphClient),
27
+ * receipt signatures (verified by GlyphClient), the SealedEnvelope's
28
+ * `inspection` report — when it removed anything, a brief note is appended
29
+ * to the MCP content so the calling model sees that sanitization happened.
30
+ * - **Lost**: the cryptographic receipt itself, the publicKey, the
31
+ * attestation envelope. MCP has nowhere to put them. This is the
32
+ * structural reason a security-conscious consumer should speak Glyph
33
+ * natively rather than through this bridge.
34
+ *
35
+ * See `spec/tests/hermes-deepseek.md` for a worked example.
36
+ */
37
+ import {
38
+ CallToolRequestSchema,
39
+ ListToolsRequestSchema,
40
+ } from '@modelcontextprotocol/sdk/types.js'
41
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
42
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
43
+ import type { GlyphClient } from '@glyphp/client'
44
+ import type { GlyphCard, SealedEnvelope } from '@glyphp/types'
45
+
46
+ export interface BridgeOptions {
47
+ /** Reported as the MCP server name on handshake. */
48
+ serverName?: string
49
+ /** Reported as the MCP server version on handshake. */
50
+ serverVersion?: string
51
+ /**
52
+ * When false, the bridge fetches the lexicon on every `tools/list` call.
53
+ * When true (default), it caches per session for speed. Cache lives for
54
+ * the lifetime of the bridge process; restart to pick up new tools.
55
+ */
56
+ cacheLexicon?: boolean
57
+ }
58
+
59
+ /**
60
+ * Builds an MCP Server that exposes a Glyph server's tools. Wire it up with
61
+ * any transport — stdio is most common.
62
+ *
63
+ * @example
64
+ * const client = new GlyphClient({ baseUrl: 'http://localhost:3199' })
65
+ * const server = mcpServerFromGlyph(client)
66
+ * await server.connect(new StdioServerTransport())
67
+ */
68
+ export function mcpServerFromGlyph(
69
+ client: GlyphClient,
70
+ options: BridgeOptions = {}
71
+ ): Server {
72
+ const server = new Server(
73
+ {
74
+ name: options.serverName ?? 'glyph-mcp-bridge',
75
+ version: options.serverVersion ?? '0.1.0',
76
+ },
77
+ { capabilities: { tools: {} } }
78
+ )
79
+
80
+ /**
81
+ * MCP tool names match OpenAI's restriction: `^[a-zA-Z0-9_-]+$`. Glyph
82
+ * allows richer names (dots, slashes) — `fs.read`, `db/query`, etc. We
83
+ * translate by replacing every disallowed character with `_` and keep a
84
+ * reverse map so `tools/call` can find the original card. Collisions are
85
+ * caught at registration time (two glyph names that normalize to the same
86
+ * MCP name throw).
87
+ */
88
+ let cardCache: Map<string, GlyphCard> | undefined
89
+ /** mcp-safe-name → original card.name */
90
+ let nameAlias: Map<string, string> | undefined
91
+
92
+ const sanitizeMcpName = (name: string): string =>
93
+ name.replace(/[^a-zA-Z0-9_-]/g, '_')
94
+
95
+ const loadCards = async (): Promise<{
96
+ cards: Map<string, GlyphCard>
97
+ alias: Map<string, string>
98
+ }> => {
99
+ if (cardCache && nameAlias && options.cacheLexicon !== false) {
100
+ return { cards: cardCache, alias: nameAlias }
101
+ }
102
+ const lexicon = await client.getLexicon()
103
+ const cards = new Map<string, GlyphCard>()
104
+ const alias = new Map<string, string>()
105
+ for (const entry of lexicon) {
106
+ const card = await client.getCard(entry.name, 'rich')
107
+ cards.set(entry.name, card)
108
+ const safe = sanitizeMcpName(entry.name)
109
+ if (alias.has(safe)) {
110
+ throw new Error(
111
+ `MCP name collision: glyph "${entry.name}" and "${alias.get(safe)}" both normalize to "${safe}". Rename one.`
112
+ )
113
+ }
114
+ alias.set(safe, entry.name)
115
+ }
116
+ cardCache = cards
117
+ nameAlias = alias
118
+ return { cards, alias }
119
+ }
120
+
121
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
122
+ const { cards } = await loadCards()
123
+ return {
124
+ tools: Array.from(cards.values()).map((card) => ({
125
+ name: sanitizeMcpName(card.name),
126
+ description: describeForMcp(card),
127
+ inputSchema: (card.input as Record<string, unknown>) ?? {
128
+ type: 'object',
129
+ },
130
+ })),
131
+ }
132
+ })
133
+
134
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
135
+ const { name, arguments: args } = req.params
136
+ const { cards, alias } = await loadCards()
137
+ // Accept either the MCP-safe name (what the model saw) or the original
138
+ // glyph name. Most clients echo the listed name verbatim.
139
+ const originalName = alias.get(name) ?? name
140
+ const card = cards.get(originalName)
141
+ if (!card) {
142
+ return {
143
+ isError: true,
144
+ content: [{ type: 'text', text: `Unknown Glyph tool: ${name}` }],
145
+ }
146
+ }
147
+ // Glyph's confirmation gate has no MCP equivalent. Refusing here surfaces
148
+ // the requirement to the model rather than silently approving — which
149
+ // would defeat the gate's purpose.
150
+ if (card.cost.requiresConfirmation) {
151
+ return {
152
+ isError: true,
153
+ content: [
154
+ {
155
+ type: 'text',
156
+ text: `Glyph tool "${name}" requires confirmation. The MCP bridge cannot satisfy this flow — call this tool via a native Glyph client that supports the prepare/confirm handshake.`,
157
+ },
158
+ ],
159
+ }
160
+ }
161
+ try {
162
+ const envelope = (await client.call(
163
+ originalName,
164
+ (args ?? {}) as Record<string, unknown>
165
+ )) as SealedEnvelope
166
+ return envelopeToMcpResult(envelope)
167
+ } catch (err) {
168
+ return {
169
+ isError: true,
170
+ content: [
171
+ {
172
+ type: 'text',
173
+ text: `Glyph call failed: ${err instanceof Error ? err.message : String(err)}`,
174
+ },
175
+ ],
176
+ }
177
+ }
178
+ })
179
+
180
+ return server
181
+ }
182
+
183
+ /**
184
+ * Builds the MCP `description` string the model sees. We surface the risk
185
+ * tier and confirmation flag in plain language so the model can reason about
186
+ * blast radius before invoking — matching the spirit of MCP's annotations
187
+ * but with the explicit Glyph vocabulary preserved.
188
+ */
189
+ function describeForMcp(card: GlyphCard): string {
190
+ const tags: string[] = []
191
+ if (card.cost.riskTier !== 'safe') {
192
+ tags.push(`risk: ${card.cost.riskTier}`)
193
+ }
194
+ if (card.cost.sideEffects) tags.push('has side effects')
195
+ if (!card.cost.reversible) tags.push('not reversible')
196
+ if (card.cost.requiresConfirmation) tags.push('requires confirmation')
197
+ const suffix = tags.length > 0 ? ` (${tags.join(', ')})` : ''
198
+ return `${card.intent}${suffix}`
199
+ }
200
+
201
+ /**
202
+ * Maps a SealedEnvelope to an MCP CallToolResult. We:
203
+ * - Encode the payload as a single text content block (JSON-stringified).
204
+ * - If sanitization removed anything, append a brief annotation so the
205
+ * model sees that Glyph defended against invisible content — this is the
206
+ * only place the bridge surfaces the security work it did.
207
+ */
208
+ function envelopeToMcpResult(envelope: SealedEnvelope): {
209
+ content: Array<{ type: string; text: string }>
210
+ } {
211
+ const blocks: Array<{ type: string; text: string }> = [
212
+ {
213
+ type: 'text',
214
+ text:
215
+ typeof envelope.payload === 'string'
216
+ ? envelope.payload
217
+ : JSON.stringify(envelope.payload, null, 2),
218
+ },
219
+ ]
220
+ const inspection = envelope.inspection
221
+ if (inspection && inspection.findings.length > 0) {
222
+ const counts = new Map<string, number>()
223
+ for (const f of inspection.findings) {
224
+ counts.set(f.kind, (counts.get(f.kind) ?? 0) + f.count)
225
+ }
226
+ const breakdown = Array.from(counts.entries())
227
+ .map(([kind, count]) => `${count} ${kind}`)
228
+ .join(', ')
229
+ const total = Array.from(counts.values()).reduce((a, b) => a + b, 0)
230
+ blocks.push({
231
+ type: 'text',
232
+ text: `[glyph: sanitized ${total} invisible character(s) from this output — ${breakdown}]`,
233
+ })
234
+ }
235
+ return { content: blocks }
236
+ }
237
+
238
+ /**
239
+ * Convenience: builds the bridge and connects it over stdio. Useful for a
240
+ * one-line bin script. Resolves once the transport is wired.
241
+ */
242
+ export async function runStdioBridge(
243
+ client: GlyphClient,
244
+ options?: BridgeOptions
245
+ ): Promise<Server> {
246
+ const server = mcpServerFromGlyph(client, options)
247
+ await server.connect(new StdioServerTransport())
248
+ return server
249
+ }
250
+
251
+ export {
252
+ mcpServerFromGlyphLazy,
253
+ runStdioBridgeLazy,
254
+ type LazyBridgeOptions,
255
+ } from './lazy.js'
package/src/lazy.ts ADDED
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Lazy bridge mode — Glyph's actual cost-saving philosophy.
3
+ *
4
+ * Where the eager bridge (in `index.ts`) dumps every card's schema into
5
+ * `tools/list` (so a 50-tool server costs ~12k tokens per turn), the lazy
6
+ * bridge exposes **only three meta-tools** to MCP:
7
+ *
8
+ * 1. `glyph_index` → cheap directory: [{name, oneLineIntent, riskTier}]
9
+ * 2. `glyph_describe` → full card for a single tool (schema, cost, etc.)
10
+ * 3. `glyph_invoke` → run the underlying glyph
11
+ *
12
+ * The model navigates: list cheap → describe what it needs → invoke. Cards
13
+ * the agent never touches never enter context. For a 50-tool server on a
14
+ * 10-turn task that touches ~6 tools, this is typically an 80-95% reduction
15
+ * in tokens spent on tool descriptions vs eager MCP, at the cost of 2 extra
16
+ * round-trips per "new" tool the agent decides to use.
17
+ *
18
+ * Trade-off (honest): smaller models may stumble. They have to "discover"
19
+ * tools rather than see them all at once. If your model can't handle that,
20
+ * use eager mode. Test, don't assume.
21
+ */
22
+ import {
23
+ CallToolRequestSchema,
24
+ ListToolsRequestSchema,
25
+ } from '@modelcontextprotocol/sdk/types.js'
26
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
27
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
28
+ import type { GlyphClient } from '@glyphp/client'
29
+ import type { GlyphCard, SealedEnvelope } from '@glyphp/types'
30
+
31
+ export interface LazyBridgeOptions {
32
+ serverName?: string
33
+ serverVersion?: string
34
+ }
35
+
36
+ const META_TOOLS = [
37
+ {
38
+ name: 'glyph_index',
39
+ description:
40
+ 'List all available Glyph tools as {name, intent, riskTier}. Cheap — call this first to see what is available, then call glyph_describe for any tool you want to use.',
41
+ inputSchema: { type: 'object', properties: {} },
42
+ },
43
+ {
44
+ name: 'glyph_describe',
45
+ description:
46
+ 'Get the full card for a single Glyph tool: input schema, output shape, side effects, reversibility, risk. Call this before glyph_invoke so you know what arguments to pass.',
47
+ inputSchema: {
48
+ type: 'object',
49
+ properties: { name: { type: 'string' } },
50
+ required: ['name'],
51
+ },
52
+ },
53
+ {
54
+ name: 'glyph_invoke',
55
+ description:
56
+ 'Invoke a Glyph tool by name with arguments. The arguments object must match the inputSchema you saw from glyph_describe. Returns the tool output.',
57
+ inputSchema: {
58
+ type: 'object',
59
+ properties: {
60
+ name: { type: 'string' },
61
+ arguments: { type: 'object' },
62
+ },
63
+ required: ['name', 'arguments'],
64
+ },
65
+ },
66
+ ]
67
+
68
+ export function mcpServerFromGlyphLazy(
69
+ client: GlyphClient,
70
+ options: LazyBridgeOptions = {}
71
+ ): Server {
72
+ const server = new Server(
73
+ {
74
+ name: options.serverName ?? 'glyph-mcp-bridge-lazy',
75
+ version: options.serverVersion ?? '0.1.0',
76
+ },
77
+ { capabilities: { tools: {} } }
78
+ )
79
+
80
+ // Card cache so describe/invoke don't re-fetch.
81
+ const cards = new Map<string, GlyphCard>()
82
+ let indexLoaded = false
83
+
84
+ async function ensureIndex(): Promise<void> {
85
+ if (indexLoaded) return
86
+ const lexicon = await client.getLexicon()
87
+ for (const entry of lexicon) {
88
+ const card = await client.getCard(entry.name, 'rich')
89
+ cards.set(entry.name, card)
90
+ }
91
+ indexLoaded = true
92
+ }
93
+
94
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
95
+ tools: META_TOOLS,
96
+ }))
97
+
98
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
99
+ const { name, arguments: args } = req.params
100
+ try {
101
+ if (name === 'glyph_index') {
102
+ await ensureIndex()
103
+ const entries = Array.from(cards.values()).map((c) => ({
104
+ name: c.name,
105
+ intent: c.intent,
106
+ riskTier: c.cost.riskTier,
107
+ }))
108
+ return {
109
+ content: [{ type: 'text', text: JSON.stringify(entries) }],
110
+ }
111
+ }
112
+ if (name === 'glyph_describe') {
113
+ await ensureIndex()
114
+ const target = (args as { name?: string } | undefined)?.name
115
+ if (!target) {
116
+ return errorResult('glyph_describe requires {name}')
117
+ }
118
+ const card = cards.get(target)
119
+ if (!card) return errorResult(`unknown glyph: ${target}`)
120
+ return {
121
+ content: [
122
+ {
123
+ type: 'text',
124
+ text: JSON.stringify({
125
+ name: card.name,
126
+ intent: card.intent,
127
+ input: card.input,
128
+ output: card.output,
129
+ cost: card.cost,
130
+ }),
131
+ },
132
+ ],
133
+ }
134
+ }
135
+ if (name === 'glyph_invoke') {
136
+ await ensureIndex()
137
+ const p = (args ?? {}) as {
138
+ name?: string
139
+ arguments?: Record<string, unknown>
140
+ }
141
+ if (!p.name) return errorResult('glyph_invoke requires {name}')
142
+ const card = cards.get(p.name)
143
+ if (!card) return errorResult(`unknown glyph: ${p.name}`)
144
+ if (card.cost.requiresConfirmation) {
145
+ return errorResult(
146
+ `glyph "${p.name}" requires confirmation; not supported via MCP bridge`
147
+ )
148
+ }
149
+ const envelope = (await client.call(
150
+ p.name,
151
+ p.arguments ?? {}
152
+ )) as SealedEnvelope
153
+ return envelopeToMcpResult(envelope)
154
+ }
155
+ return errorResult(`unknown meta-tool: ${name}`)
156
+ } catch (err) {
157
+ return errorResult(
158
+ `lazy bridge error: ${err instanceof Error ? err.message : String(err)}`
159
+ )
160
+ }
161
+ })
162
+
163
+ return server
164
+ }
165
+
166
+ function errorResult(msg: string): {
167
+ isError: boolean
168
+ content: Array<{ type: string; text: string }>
169
+ } {
170
+ return { isError: true, content: [{ type: 'text', text: msg }] }
171
+ }
172
+
173
+ function envelopeToMcpResult(envelope: SealedEnvelope): {
174
+ content: Array<{ type: string; text: string }>
175
+ } {
176
+ const blocks: Array<{ type: string; text: string }> = [
177
+ {
178
+ type: 'text',
179
+ text:
180
+ typeof envelope.payload === 'string'
181
+ ? envelope.payload
182
+ : JSON.stringify(envelope.payload),
183
+ },
184
+ ]
185
+ const inspection = envelope.inspection
186
+ if (inspection && inspection.findings.length > 0) {
187
+ const counts = new Map<string, number>()
188
+ for (const f of inspection.findings) {
189
+ counts.set(f.kind, (counts.get(f.kind) ?? 0) + f.count)
190
+ }
191
+ const breakdown = Array.from(counts.entries())
192
+ .map(([k, n]) => `${n} ${k}`)
193
+ .join(', ')
194
+ const total = Array.from(counts.values()).reduce((a, b) => a + b, 0)
195
+ blocks.push({
196
+ type: 'text',
197
+ text: `[glyph: sanitized ${total} invisible character(s) — ${breakdown}]`,
198
+ })
199
+ }
200
+ return { content: blocks }
201
+ }
202
+
203
+ export async function runStdioBridgeLazy(
204
+ client: GlyphClient,
205
+ options?: LazyBridgeOptions
206
+ ): Promise<Server> {
207
+ const server = mcpServerFromGlyphLazy(client, options)
208
+ await server.connect(new StdioServerTransport())
209
+ return server
210
+ }