@showmeonmap/mcp 0.2.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,166 @@
1
+ # @showmeonmap/mcp
2
+
3
+ [Model Context Protocol](https://modelcontextprotocol.io/) server for [ShowMeOnMap](https://github.com/FrankAIUser/showmeonmap). Lets any MCP-speaking agent — Claude Desktop, Cursor, Zed, Windsurf, ChatGPT Apps SDK, custom LangGraph / CrewAI / Autogen agents — build and mutate geospatial maps over a typed tool surface.
4
+
5
+ **Spec:** `docs/superpowers/specs/2026-04-17-mcp-server-design.md` (in the parent repo).
6
+
7
+ ---
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npx -y @showmeonmap/mcp
13
+ ```
14
+
15
+ That's it. Or pin a version: `npx -y @showmeonmap/mcp@0.2.0`.
16
+
17
+ The server speaks standard MCP/stdio; it's a thin proxy to the ShowMeOnMap HTTP API. Point it at production with your API key (below), or at a local checkout (default: `http://localhost:3000`).
18
+
19
+ ---
20
+
21
+ ## Get an API key (production)
22
+
23
+ 1. Sign in at [showmeonmap.com](https://showmeonmap.com) and buy a credit pack (`/pricing`).
24
+ 2. Account menu → **API keys** → **Create key**. Copy the `smo_live_…` key — it's shown once.
25
+ 3. Every map your agent builds spends **your credits** at the same rates as the web app (1 credit per standard map or mutation, 3 per agent-grade map; reads are free). Refunds are automatic on failures.
26
+
27
+ **Prefer no local process?** Use the hosted remote endpoint directly — no install:
28
+
29
+ ```json
30
+ {
31
+ "mcpServers": {
32
+ "showmeonmap": {
33
+ "url": "https://showmeonmap.com/api/mcp",
34
+ "headers": { "Authorization": "Bearer smo_live_…" }
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ The hosted endpoint speaks streamable HTTP (stateless), is rate-limited to 30 requests/min per key, and works anywhere remote MCP servers do — Claude custom connectors, the OpenAI Responses API (`server_url`), Gemini managed agents (`mcp_server`), Cursor, Copilot Studio, Bedrock.
41
+
42
+ ---
43
+
44
+ ## Wire into Claude Desktop
45
+
46
+ Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS):
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "showmeonmap": {
52
+ "command": "npx",
53
+ "args": ["-y", "@showmeonmap/mcp"],
54
+ "env": {
55
+ "SHOWMEONMAP_BASE_URL": "https://showmeonmap.com",
56
+ "SHOWMEONMAP_API_KEY": "smo_live_…"
57
+ }
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ Restart Claude Desktop. `showmeonmap` appears in the tools picker.
64
+
65
+ Cursor (`~/.cursor/mcp.json`), Zed, Windsurf, and any other MCP host follow the same shape — `command: "npx"`, `args: ["-y", "@showmeonmap/mcp"]`, plus the `SHOWMEONMAP_BASE_URL` + `SHOWMEONMAP_API_KEY` env. For local dev against a checkout, drop the key and set `SHOWMEONMAP_BASE_URL=http://localhost:3000`.
66
+
67
+ ---
68
+
69
+ ## Run a ShowMeOnMap backend locally
70
+
71
+ The package is a client; you also need a backend. From a checkout of [the main repo](https://github.com/FrankAIUser/showmeonmap):
72
+
73
+ ```bash
74
+ SMO_DISABLE_AUTH=1 SMO_DISABLE_CREDIT_GATE=1 SMO_DISABLE_RATE_LIMIT=1 npm run dev
75
+ ```
76
+
77
+ (In production, point `SHOWMEONMAP_BASE_URL` at the hosted backend instead.)
78
+
79
+ ---
80
+
81
+ ## Try it
82
+
83
+ Ask Claude Desktop things like:
84
+
85
+ - *"Build me a map of volcanoes in Japan"* → invokes `build_map`, returns a `map_id` + structured response
86
+ - *"Now filter to ones above 2000m elevation"* → invokes `mutate_map`, applies a `filterLayer` op
87
+ - *"Change the basemap to satellite"* → another `mutate_map` with `setBasemap`
88
+ - *"Show me recent earthquakes"* (unrelated) → `outOfScope` triggers; Claude can fall back to `build_map`
89
+ - *"Remove it"* (with a multi-layer map) → `clarification` with candidates
90
+
91
+ ---
92
+
93
+ ## Tool surface (24 tools)
94
+
95
+ **V1 — natural-language tools (3)**: `build_map`, `mutate_map`, `get_state`.
96
+ **V2 — direct-op tools (18)**: `add_layer`, `filter_layer`, `clear_filters`, `remove_layer`, `rename_layer`, `restyle_layer`, `set_camera`, `set_time`, `set_basemap`, `select_within`, `subset_to_selection`, `query_features`, `add_annotation`, `remove_annotation`, `tag`, `undo`, `redo`, `report_blocker`.
97
+
98
+ Every tool returns a **three-channel envelope**:
99
+
100
+ ```json
101
+ {
102
+ "ok": true,
103
+ "map_id": "…",
104
+ "version": 5,
105
+ "structured": { "workspace": {…}, "mapPlan": {…} },
106
+ "shareable_url": "http://localhost:3000/m/…",
107
+ "metadata": { "title": "…", "layer_count": 2, "last_updated": "…" },
108
+ "next_actions": [
109
+ { "label": "Filter to features where name is not empty", "argsTemplate": { "instruction": "…" } }
110
+ ],
111
+ "outOfScope": { "reason": "…" },
112
+ "clarification": { "question": "…", "candidates": [ … ] }
113
+ }
114
+ ```
115
+
116
+ The calling agent reasons over `structured`, surfaces `shareable_url` to its end user for interactive drill-down, and uses `next_actions` as typed hints for follow-up tool calls.
117
+
118
+ For the full Op catalog and predicate grammar that the V2 tools accept, fetch the MCP resource at `showmeonmap://docs/workspace-ops-spec` — agents should not guess these shapes.
119
+
120
+ ---
121
+
122
+ ## Environment variables
123
+
124
+ | Var | Default | Purpose |
125
+ |---|---|---|
126
+ | `SHOWMEONMAP_BASE_URL` | `http://localhost:3000` | Where the ShowMeOnMap HTTP API lives |
127
+ | `SHOWMEONMAP_API_KEY` | (unset) | Your personal `smo_live_…` key — identifies you and spends your credits. Required against production; optional for a local dev checkout running with auth bypasses |
128
+ | `MCP_BLOCKER_LOG_PATH` | `reports/agent-blockers/<today>.ndjson` (in the backend's cwd) | Where `report_blocker` tool calls are appended |
129
+ | `MCP_RATIONALE_LOG_PATH` | `reports/mcp-rationale/<today>.ndjson` | Where typed-op rationales are persisted |
130
+
131
+ ---
132
+
133
+ ## Run from a checkout (debugging)
134
+
135
+ If you have the main repo cloned and want to run the unbuilt source:
136
+
137
+ ```bash
138
+ npm --prefix packages/mcp-server install
139
+ npm --prefix packages/mcp-server run build
140
+ node packages/mcp-server/dist/index.js
141
+ ```
142
+
143
+ The integration test (requires backend on `localhost:3000`):
144
+
145
+ ```bash
146
+ npx tsx packages/mcp-server/__tests__/stdio-roundtrip.test.ts
147
+ ```
148
+
149
+ Spawns a fresh server process, exercises `initialize` → `tools/list` → every tool over NDJSON-framed JSON-RPC, asserts envelope shape. Exits 0 with a "skipping" notice if the backend isn't reachable.
150
+
151
+ ---
152
+
153
+ ## Current limitations
154
+
155
+ - **In-memory session cache.** `map_id` → workspace mapping lives in the server process; restarts lose state. Phase I-3 (in the parent repo's plan) wires D1 persistence so `shareable_url` actually resolves across sessions.
156
+ - **No preview PNG.** The envelope's `shareable_url` points at the app's `/m/<id>` viewer, but workspaces aren't yet persisted in the gallery. Until I-3, share the raw structured response.
157
+ - **stdio bin + hosted remote endpoint.** This package's bin is stdio; remote hosts use `https://showmeonmap.com/api/mcp` (streamable HTTP, stateless). The standalone Node HTTP entry (`packages/mcp-server/src/http.ts`) remains for self-hosting a checkout.
158
+ - **Auth is per-user API keys** (`smo_live_…`, minted at showmeonmap.com). The key travels as a bearer on every backend call and bills the key's owner.
159
+
160
+ ---
161
+
162
+ ## References
163
+
164
+ - Protocol: [modelcontextprotocol.io](https://modelcontextprotocol.io/)
165
+ - SDK: [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk)
166
+ - Repo: [github.com/FrankAIUser/showmeonmap](https://github.com/FrankAIUser/showmeonmap)
package/dist/http.js ADDED
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ShowMeOnMap MCP server — Streamable HTTP transport (M-2)
4
+ *
5
+ * Exposes the same three tools as the stdio transport (build_map, mutate_map,
6
+ * get_state) over HTTP per the MCP Streamable HTTP spec. Intended for remote
7
+ * MCP clients (hosted Claude Desktop, ChatGPT Apps SDK, future A2A peers)
8
+ * that can't spawn a local subprocess.
9
+ *
10
+ * Protocol:
11
+ * - POST /mcp — JSON-RPC requests (and batch requests)
12
+ * - GET /mcp — server-push via SSE (optional upgrade)
13
+ * - Mcp-Session-Id header — opaque per-session id returned on init
14
+ *
15
+ * Auth (baseline): single shared bearer token via MCP_HTTP_AUTH_TOKEN env var.
16
+ * If set, every request must include `Authorization: Bearer <token>`. If
17
+ * unset the server runs open — fine for localhost dev, unacceptable for a
18
+ * public deployment.
19
+ *
20
+ * Run:
21
+ * MCP_HTTP_AUTH_TOKEN=dev npx tsx packages/mcp-server/src/http.ts
22
+ *
23
+ * Test with a curl that speaks JSON-RPC:
24
+ * curl -H 'Authorization: Bearer dev' -H 'Content-Type: application/json' \
25
+ * -H 'Accept: application/json, text/event-stream' \
26
+ * http://localhost:3333/mcp -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
27
+ *
28
+ * Or point Claude Desktop at it:
29
+ * {
30
+ * "mcpServers": {
31
+ * "showmeonmap-remote": {
32
+ * "url": "http://localhost:3333/mcp",
33
+ * "transport": "http",
34
+ * "headers": { "Authorization": "Bearer dev" }
35
+ * }
36
+ * }
37
+ * }
38
+ *
39
+ * Spec: docs/superpowers/specs/2026-04-17-mcp-server-design.md
40
+ */
41
+ import { createServer as createHttpServer } from 'node:http';
42
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
43
+ import { randomUUID } from 'node:crypto';
44
+ import { createServer as createMcpServer } from "./tools.js";
45
+ const BASE_URL = process.env.SHOWMEONMAP_BASE_URL ?? 'http://localhost:3000';
46
+ const API_KEY = process.env.SHOWMEONMAP_API_KEY;
47
+ const HTTP_PORT = Number(process.env.MCP_HTTP_PORT ?? 3333);
48
+ const AUTH_TOKEN = process.env.MCP_HTTP_AUTH_TOKEN;
49
+ const ENDPOINT_PATH = '/mcp';
50
+ /**
51
+ * Default to the in-memory store. Production deployments running under a
52
+ * Cloudflare Worker (where a D1 binding exists) should construct their
53
+ * own SessionStore via createD1SessionStore from sessionStoreD1.ts and
54
+ * either:
55
+ *
56
+ * - import this http handler as a module and pass `sessionStore` to
57
+ * createMcpServer there, or
58
+ * - swap to running the MCP transport inside the Worker fetch handler
59
+ * and inject the binding directly.
60
+ *
61
+ * The standalone Node entrypoint below has no access to a D1 binding, so
62
+ * it deliberately stays in-memory. See docs/claude-refs/mcp-server.md
63
+ * "D1 SessionStore" for the production wiring pattern.
64
+ */
65
+ const SHARED_SESSION_STORE = undefined;
66
+ // ── Per-session transport registry ─────────────────────────────────────
67
+ // MCP Streamable HTTP uses one transport instance per session. Sessions
68
+ // are identified by the Mcp-Session-Id header, which the client sends
69
+ // starting with its second request (the init response sets it). We keep
70
+ // a registry so that mid-session POST /mcp and GET /mcp reach the right
71
+ // transport.
72
+ const transports = new Map();
73
+ // ── Auth check ────────────────────────────────────────────────────────
74
+ function isAuthorized(req) {
75
+ if (!AUTH_TOKEN)
76
+ return true; // open mode
77
+ const hdr = req.headers['authorization'];
78
+ if (typeof hdr !== 'string')
79
+ return false;
80
+ if (!hdr.startsWith('Bearer '))
81
+ return false;
82
+ return hdr.slice(7).trim() === AUTH_TOKEN;
83
+ }
84
+ function writeJson(res, status, body) {
85
+ res.statusCode = status;
86
+ res.setHeader('Content-Type', 'application/json');
87
+ res.end(JSON.stringify(body));
88
+ }
89
+ function isInitializeRequest(payload) {
90
+ if (!payload || typeof payload !== 'object')
91
+ return false;
92
+ const p = payload;
93
+ return p.method === 'initialize';
94
+ }
95
+ async function readBody(req) {
96
+ const chunks = [];
97
+ for await (const chunk of req)
98
+ chunks.push(chunk);
99
+ const raw = Buffer.concat(chunks).toString('utf8');
100
+ if (!raw)
101
+ return null;
102
+ try {
103
+ return JSON.parse(raw);
104
+ }
105
+ catch {
106
+ throw new Error(`invalid JSON body: ${raw.slice(0, 200)}`);
107
+ }
108
+ }
109
+ async function handleRequest(req, res) {
110
+ // Normalize path
111
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
112
+ if (url.pathname !== ENDPOINT_PATH) {
113
+ writeJson(res, 404, { error: 'not_found', message: `POST or GET ${ENDPOINT_PATH}` });
114
+ return;
115
+ }
116
+ if (!isAuthorized(req)) {
117
+ writeJson(res, 401, { error: 'unauthorized', message: 'missing or invalid Bearer token' });
118
+ return;
119
+ }
120
+ const sessionId = req.headers['mcp-session-id'];
121
+ const sessionIdStr = typeof sessionId === 'string' ? sessionId : undefined;
122
+ // Fast path: existing session
123
+ if (sessionIdStr && transports.has(sessionIdStr)) {
124
+ const transport = transports.get(sessionIdStr);
125
+ if (req.method === 'POST') {
126
+ let body;
127
+ try {
128
+ body = await readBody(req);
129
+ }
130
+ catch (err) {
131
+ writeJson(res, 400, { error: 'bad_request', message: err.message });
132
+ return;
133
+ }
134
+ await transport.handleRequest(req, res, body);
135
+ return;
136
+ }
137
+ await transport.handleRequest(req, res); // GET (SSE) or DELETE (close)
138
+ return;
139
+ }
140
+ // New session — only valid on POST of an initialize request.
141
+ if (req.method !== 'POST') {
142
+ writeJson(res, 400, { error: 'bad_request', message: 'missing Mcp-Session-Id header — send initialize via POST first' });
143
+ return;
144
+ }
145
+ let body;
146
+ try {
147
+ body = await readBody(req);
148
+ }
149
+ catch (err) {
150
+ writeJson(res, 400, { error: 'bad_request', message: err.message });
151
+ return;
152
+ }
153
+ if (!isInitializeRequest(body)) {
154
+ writeJson(res, 400, { error: 'bad_request', message: 'first request must be initialize' });
155
+ return;
156
+ }
157
+ const transport = new StreamableHTTPServerTransport({
158
+ sessionIdGenerator: () => randomUUID(),
159
+ onsessioninitialized: (id) => {
160
+ transports.set(id, transport);
161
+ process.stderr.write(`[showmeonmap-mcp-http] session opened: ${id}\n`);
162
+ },
163
+ });
164
+ transport.onclose = () => {
165
+ const sid = transport.sessionId;
166
+ if (sid && transports.has(sid)) {
167
+ transports.delete(sid);
168
+ process.stderr.write(`[showmeonmap-mcp-http] session closed: ${sid}\n`);
169
+ }
170
+ };
171
+ const mcpServer = createMcpServer({
172
+ baseUrl: BASE_URL,
173
+ apiKey: API_KEY,
174
+ sessionStore: SHARED_SESSION_STORE,
175
+ });
176
+ await mcpServer.connect(transport);
177
+ await transport.handleRequest(req, res, body);
178
+ }
179
+ const server = createHttpServer((req, res) => {
180
+ handleRequest(req, res).catch((err) => {
181
+ process.stderr.write(`[showmeonmap-mcp-http] unhandled: ${err instanceof Error ? err.stack : String(err)}\n`);
182
+ if (!res.headersSent) {
183
+ writeJson(res, 500, { error: 'internal', message: err.message });
184
+ }
185
+ });
186
+ });
187
+ server.listen(HTTP_PORT, () => {
188
+ const authStatus = AUTH_TOKEN ? 'bearer-auth enabled' : 'OPEN (no auth — dev only)';
189
+ process.stderr.write(`[showmeonmap-mcp-http] listening on http://127.0.0.1:${HTTP_PORT}${ENDPOINT_PATH} · base=${BASE_URL} · ${authStatus}\n`);
190
+ });
191
+ // Graceful shutdown — close every live session so clients see DELETE, not a socket hangup.
192
+ async function shutdown() {
193
+ process.stderr.write(`[showmeonmap-mcp-http] shutting down · ${transports.size} sessions\n`);
194
+ for (const t of transports.values()) {
195
+ try {
196
+ await t.close();
197
+ }
198
+ catch { /* swallow */ }
199
+ }
200
+ server.close(() => process.exit(0));
201
+ setTimeout(() => process.exit(0), 2000).unref();
202
+ }
203
+ process.on('SIGINT', shutdown);
204
+ process.on('SIGTERM', shutdown);
package/dist/index.js ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ShowMeOnMap MCP server — stdio transport (M-1)
4
+ *
5
+ * Exposes the ShowMeOnMap agent-emission architecture as MCP tools that
6
+ * Claude Desktop, Cursor, Zed, Windsurf, ChatGPT Apps SDK, or any other
7
+ * MCP host can consume over stdio.
8
+ *
9
+ * For the HTTP/SSE transport (M-2), see `http.ts`. Both transports share
10
+ * the same tool implementations via `tools.ts::createServer`.
11
+ *
12
+ * Spec: docs/superpowers/specs/2026-04-17-mcp-server-design.md
13
+ *
14
+ * Run manually (from a checkout):
15
+ * npx tsx packages/mcp-server/src/index.ts
16
+ *
17
+ * Or via the published package (Claude Desktop / Cursor / etc.):
18
+ * {
19
+ * "mcpServers": {
20
+ * "showmeonmap": {
21
+ * "command": "npx",
22
+ * "args": ["-y", "@showmeonmap/mcp"],
23
+ * "env": {
24
+ * "SHOWMEONMAP_BASE_URL": "http://localhost:3000",
25
+ * "SHOWMEONMAP_API_KEY": "<optional-for-auth>"
26
+ * }
27
+ * }
28
+ * }
29
+ * }
30
+ */
31
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
32
+ import { createServer } from "./tools.js";
33
+ const BASE_URL = process.env.SHOWMEONMAP_BASE_URL ?? 'http://localhost:3000';
34
+ const API_KEY = process.env.SHOWMEONMAP_API_KEY;
35
+ async function main() {
36
+ // The stdio transport is launched as a child process by Claude Desktop /
37
+ // Cursor / etc. — there is no Cloudflare D1 binding available here. The
38
+ // in-memory store (default) is correct for this environment. Production
39
+ // HTTP transport opts into D1 separately via http.ts. Callers can override
40
+ // by injecting their own SessionStore into createServer if needed.
41
+ const sessionStore = undefined;
42
+ const server = createServer({ baseUrl: BASE_URL, apiKey: API_KEY, sessionStore });
43
+ const transport = new StdioServerTransport();
44
+ await server.connect(transport);
45
+ process.stderr.write(`[showmeonmap-mcp] stdio ready · base=${BASE_URL}\n`);
46
+ }
47
+ main().catch((err) => {
48
+ process.stderr.write(`[showmeonmap-mcp] fatal: ${err instanceof Error ? err.stack : String(err)}\n`);
49
+ process.exit(1);
50
+ });