@embd/mcp 0.1.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/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # @embd/mcp
2
+
3
+ MCP server for [embd](https://www.embd.sh) — hosted, embeddable charts and docs.
4
+
5
+ Connect it to an AI agent and the agent can turn any tabular data it is working
6
+ with — CSV files, query results, scraped tables, computed metrics — into a
7
+ hosted chart on embd.sh and hand back a shareable link and a ready-to-paste
8
+ `<iframe>` embed snippet, without the user ever opening a chart editor. It can
9
+ also publish rendered documents — HTML pages or markdown write-ups it has
10
+ generated — as hosted, embeddable pages (`create_doc`). Agents can list every
11
+ embed owned by the account and delete ones that are no longer needed, so embed
12
+ management can happen entirely inside a conversation.
13
+
14
+ ## Setup
15
+
16
+ You need an embd API key (starts with `embd_sk_`). Create one in your embd
17
+ account settings at [www.embd.sh](https://www.embd.sh). API access is free
18
+ during the beta; after launch it will require a Pro plan.
19
+
20
+ The published package is bundled for plain Node.js (>= 18) — `npx` and `bunx`
21
+ both work. The snippets below apply **once the package is published to npm**;
22
+ from a checkout of this repo, run the server directly instead:
23
+ `EMBD_API_KEY=embd_sk_... bun src/bin.ts`.
24
+
25
+ ### Claude Code
26
+
27
+ ```sh
28
+ claude mcp add embd -e EMBD_API_KEY=embd_sk_... -- npx @embd/mcp
29
+ ```
30
+
31
+ ### Claude Desktop
32
+
33
+ Add to `claude_desktop_config.json`:
34
+
35
+ ```json
36
+ {
37
+ "mcpServers": {
38
+ "embd": {
39
+ "command": "npx",
40
+ "args": ["@embd/mcp"],
41
+ "env": {
42
+ "EMBD_API_KEY": "embd_sk_..."
43
+ }
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ ## Environment variables
50
+
51
+ | Variable | Required | Description |
52
+ | -------------- | -------- | -------------------------------------------------------- |
53
+ | `EMBD_API_KEY` | yes | embd API key (`embd_sk_...`) |
54
+ | `EMBD_API_URL` | no | Override the API base URL (useful for local development) |
55
+
56
+ ## Tools
57
+
58
+ | Tool | Input | Result |
59
+ | -------------- | -------------------------------------------------------------- | ----------------------------------------------- |
60
+ | `create_chart` | `data` (CSV text or array of row objects), plus optional `kind`, `title`, `x`, `y`, `split`, `theme`, `publish` | Hosted URL, iframe embed snippet, and chart id |
61
+ | `create_doc` | `content` (HTML or markdown text, max 100,000 chars), `format` (`html` \| `markdown`), plus optional `title`, `publish` | Hosted URL, iframe embed snippet, and doc id |
62
+ | `list_charts` | — | Your embeds (charts and docs), newest first: `id — kind — status — title — url` |
63
+ | `delete_chart` | `id` | Deletion confirmation (charts and docs alike) |
64
+
65
+ Use `create_chart` when tabular data should become a chart; use `create_doc`
66
+ when the deliverable is the document itself — a report, write-up, or
67
+ self-contained HTML page. Hosted HTML renders inside a sandboxed iframe with
68
+ **JavaScript disabled** — scripts never run, handlers never fire, forms cannot
69
+ submit; CSS, images, web fonts and inline SVG work normally, so send static
70
+ HTML and pre-render anything interactive. `create_doc` warns when the content
71
+ it is given needs features the sandbox drops. Markdown gets a clean default
72
+ stylesheet. In `list_charts` output, a doc's kind is its format (`html` or
73
+ `markdown`).
74
+
75
+ Published charts and docs are **public**: anyone with the URL can view them.
76
+ Pass `publish: false` to `create_chart` or `create_doc` to save a private
77
+ draft instead.
78
+
79
+ Chart kinds: `line` (default), `area`, `bar`, `stacked-bar`, `stacked-area`,
80
+ `bar-horizontal`, `scatter`, `pie`, `donut`, `heatmap`, `radar`.
81
+
82
+ Themes: `aurora`, `simple`, `vibrant`, `neon` — each in `-light` and `-dark`
83
+ (e.g. `aurora-dark`, the default).
84
+
85
+ ## Remote (HTTP) server — stateless, no key (WEB-MCP)
86
+
87
+ The tools above run over **stdio** and require an API key, because they persist
88
+ hosted embeds through the embd API. That works for a locally-spawned server
89
+ (Claude Desktop / Claude Code) but **cannot back a remote connector**: a ChatGPT
90
+ app or a Claude.ai / Cowork custom connector needs an MCP server reachable over
91
+ **HTTP**.
92
+
93
+ `embd-mcp-http` is that server, and it is deliberately **stateless and
94
+ key-free**. Every tool is a pure function over `@embd/core`'s URL builders: data
95
+ in → a self-contained `embd.sh/#…` link out, with the content encoded directly
96
+ in the URL fragment (ADR-0004/0008). Nothing is stored, no account is touched,
97
+ and there is no privileged action — so the endpoint is safe to expose with **no
98
+ auth**, which also means no demo account is needed for OpenAI's app review.
99
+
100
+ ```sh
101
+ # from a checkout
102
+ EMBD_MCP_HOST=0.0.0.0 EMBD_MCP_PORT=8787 bun src/http-bin.ts
103
+ # or the built binary
104
+ node dist/http-bin.js
105
+ ```
106
+
107
+ Then point a client at `http://<host>:<port>/mcp` (Streamable HTTP). A quick check:
108
+
109
+ ```sh
110
+ curl -s -X POST http://127.0.0.1:8787/mcp \
111
+ -H 'Content-Type: application/json' \
112
+ -H 'Accept: application/json, text/event-stream' \
113
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
114
+ ```
115
+
116
+ Stateless tools: `create_chart`, `create_doc` (markdown only), `create_kpi`,
117
+ `create_qr` — each returns `{ url, kind }` in `structuredContent`. All are
118
+ declared read-only / non-destructive.
119
+
120
+ **Token discipline:** a stateless link carries its data inline, so the URL *is*
121
+ the payload — kept bounded by the share-limit guard. Data too large to fit a
122
+ link returns a typed error (use the hosted stdio server for that), so an
123
+ oversized base64 blob never lands in the model's context.
124
+
125
+ ### HTTP environment variables
126
+
127
+ | Variable | Default | Description |
128
+ | ------------------------ | ------------------- | --------------------------------------------------------------- |
129
+ | `PORT` / `EMBD_MCP_PORT` | `8787` | Listen port |
130
+ | `EMBD_MCP_HOST` | `127.0.0.1` | Bind address (`0.0.0.0` in a container) |
131
+ | `EMBD_MCP_PATH` | `/mcp` | MCP endpoint path |
132
+ | `EMBD_ORIGIN` | `https://embd.sh` | Origin for the URLs the tools return |
133
+ | `EMBD_MCP_ALLOWED_HOSTS` | — | Comma-separated Host allowlist; enables DNS-rebinding protection |
134
+
135
+ ### Deploy (owner)
136
+
137
+ Not deployed by CI. The endpoint needs an HTTPS host reachable by ChatGPT /
138
+ Claude (any Node host, or a container). Once live: add it as a **custom
139
+ connector** in Claude/Cowork, or load it in **ChatGPT developer mode**, pointed
140
+ at `https://<host>/mcp`. Public ChatGPT-app submission additionally needs a CSP
141
+ whitelisting the widget's fetch domains — deferred with the MCP Apps widget
142
+ layer (see below).
143
+
144
+ ### Not yet built (follow-ups on the WEB-MCP ticket)
145
+
146
+ - **MCP Apps widget** (`@modelcontextprotocol/ext-apps`) — an inline UI
147
+ rendering the embed in ChatGPT/Claude. Deferred: it needs a real host client
148
+ to verify and a CSP with CONNECTED-DATA disabled. The transport + tools here
149
+ are the load-bearing half and work without it.
150
+ - **Hosted short-link mode over HTTP** — for data too big for a stateless URL,
151
+ an authenticated variant returning a short id (the stdio server already does
152
+ this locally).
153
+
154
+ ## Development
155
+
156
+ ```sh
157
+ bun test # unit + HTTP integration tests (no network; stateless tools hit real @embd/core)
158
+ bun run typecheck
159
+ bun run lint
160
+ bun run build # bundles src/{bin,http-bin,index}.ts -> dist/ (node target; the published bins)
161
+ EMBD_API_KEY=embd_sk_... bun src/bin.ts # run the stdio (hosted) server directly
162
+ bun src/http-bin.ts # run the stateless HTTP server directly (no key)
163
+ ```
@@ -0,0 +1,14 @@
1
+ import{D as $Z,h as G,i as MZ,j as C,k as z,l as v,m as S,n as c,o as l,u as s,v as o,w as r,x as e,y as ZZ}from"./bin-q5p2211j.js";var VZ=["line","area","bar","stacked-bar","stacked-area","bar-horizontal","scatter","pie","donut","heatmap","radar"],E=["stage","slate","dusk","paper","mist","sepia"];function H(Z,$){return{content:[{type:"text",text:Z}],structuredContent:{url:Z,kind:$}}}function k(Z){return{content:[{type:"text",text:Z instanceof Error?Z.message:String(Z)}],isError:!0}}async function LZ(Z,$={}){try{let Q=await o(Z.data,{origin:$.origin,kind:Z.kind,title:Z.title,themeId:Z.theme});return H(Q,"chart")}catch(Q){return k(Q)}}async function UZ(Z,$={}){try{let Q=await r(Z.content,{origin:$.origin,theme:Z.theme});return H(Q,"markdown")}catch(Q){return k(Q)}}async function fZ(Z,$={}){try{let Q=await e(Z,{origin:$.origin});return H(Q,"kpi")}catch(Q){return k(Q)}}async function AZ(Z,$={}){try{let Q=await ZZ(Z,{origin:$.origin});return H(Q,"qr")}catch(Q){return k(Q)}}var O={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!1},_Z=["create_kpi"];function QZ(Z={}){let $=new s({name:"embd",version:$Z});if($.registerTool("create_chart",{title:"Create a shareable embd chart link",description:"Turn tabular data into a beautiful, shareable chart and return a self-contained embd.sh URL. "+"No account, no upload, no API call — the chart data is encoded directly into the returned link, "+"so it works anywhere and needs no backend. Use this when you have data (CSV text or an array of flat JSON row objects) and the user wants a chart they can link to, share, or embed. "+"Column roles are inferred automatically (first non-numeric column → X axis, numeric columns → "+"series). Because the data rides in the URL, there is a size limit — if the data is too large the "+"tool returns an error asking you to reduce it; very large datasets need the hosted embd server instead.",inputSchema:G.object({data:G.union([G.string(),G.array(G.record(G.string(),G.unknown()))]).describe('CSV text (first row = headers) or an array of flat row objects with identical keys, e.g. [{"month":"Jan","sales":120}, ...].'),kind:G.enum(VZ).optional().describe("Chart type. Default: inferred from the data (usually line or bar)."),title:G.string().optional().describe("Chart title."),theme:G.string().optional().describe("Theme id (e.g. aurora-dark, aurora-light). Default: aurora-dark.")}),annotations:O},async(Q)=>LZ(Q,Z)),$.registerTool("create_doc",{title:"Create a shareable embd markdown doc link",description:"Render Markdown into a clean, shareable page and return a self-contained embd.sh URL. "+"No account and no upload — the Markdown source is encoded into the link. Use this for a report, "+"write-up, or formatted notes the user wants to share as a link. Markdown only (HTML documents require the hosted embd server). Large documents may exceed the URL size limit and return an error.",inputSchema:G.object({content:G.string().describe("The Markdown source text."),theme:G.enum(E).optional().describe("Reading theme. Default: stage.")}),annotations:O},async(Q)=>UZ(Q,Z)),!_Z.includes("create_kpi"))$.registerTool("create_kpi",{title:"Create a shareable embd KPI/stat link",description:"Build a big-number KPI card (value + label, optional change indicator, caption and sparkline) and "+"return a self-contained embd.sh URL. No account or upload — the card is encoded into the link. "+'Values are pre-formatted strings (you format them, e.g. "$1.2M", "98%").',inputSchema:G.object({value:G.string().describe('The big value, pre-formatted (e.g. "$1.2M", "98%").'),label:G.string().describe('What it measures (e.g. "Monthly revenue").'),caption:G.string().optional().describe("Optional sub-line (context or timeframe)."),delta:G.object({value:G.string().describe('Displayed change, e.g. "12%" or "340".'),dir:G.enum(["up","down","flat"]).describe("Arrow direction."),good:G.boolean().optional().describe("Whether this direction reads as positive (drives color). Default: up=good.")}).optional().describe("Optional change indicator."),sparkline:G.array(G.number()).optional().describe("Optional trend series (numbers) drawn behind the value."),theme:G.enum(E).optional().describe("Reading theme. Default: stage.")}),annotations:O},async(Q)=>fZ(Q,Z));return $.registerTool("create_qr",{title:"Create a shareable embd QR-code link",description:"Generate a styled QR code for a URL or text and return a self-contained embd.sh URL that renders it. No account or upload. Supports an optional heading, caption, foreground/background hex colors, and a small center emoji icon.",inputSchema:G.object({content:G.string().describe("What the QR encodes (a URL, text, …)."),label:G.string().optional().describe("Optional heading above the code."),caption:G.string().optional().describe("Optional sub-line below it."),fg:G.string().optional().describe("Module (foreground) color as a 6-digit hex."),bg:G.string().optional().describe("Background color as a 6-digit hex."),icon:G.string().optional().describe("A small center emoji icon."),theme:G.enum(E).optional().describe("Reading theme. Default: stage.")}),annotations:O},async(Q)=>AZ(Q,Z)),$}import{createServer as hZ}from"node:http";import{Http2ServerRequest as YZ,constants as DZ}from"http2";import{Http2ServerRequest as I}from"http2";import{Readable as WZ}from"stream";import vZ from"crypto";var V=class extends Error{constructor(Z,$){super(Z,$);this.name="RequestError"}},NZ=(Z)=>{if(Z instanceof V)return Z;return new V(Z.message,{cause:Z})},TZ=global.Request,N=class extends TZ{constructor(Z,$){if(typeof Z==="object"&&_ in Z)Z=Z[_]();if(typeof $?.body?.getReader<"u")$.duplex??="half";super(Z,$)}},zZ=(Z)=>{let $=[],Q=Z.rawHeaders;for(let W=0;W<Q.length;W+=2){let{[W]:X,[W+1]:Y}=Q;if(X.charCodeAt(0)!==58)$.push([X,Y])}return new Headers($)},jZ=Symbol("wrapBodyStream"),PZ=(Z,$,Q,W,X)=>{let Y={method:Z,headers:Q,signal:X.signal};if(Z==="TRACE"){Y.method="GET";let j=new N($,Y);return Object.defineProperty(j,"method",{get(){return"TRACE"}}),j}if(!(Z==="GET"||Z==="HEAD"))if("rawBody"in W&&W.rawBody instanceof Buffer)Y.body=new ReadableStream({start(j){j.enqueue(W.rawBody),j.close()}});else if(W[jZ]){let j;Y.body=new ReadableStream({async pull(x){try{j||=WZ.toWeb(W).getReader();let{done:B,value:K}=await j.read();if(B)x.close();else x.enqueue(K)}catch(B){x.error(B)}}})}else Y.body=WZ.toWeb(W);return new N($,Y)},_=Symbol("getRequestCache"),xZ=Symbol("requestCache"),w=Symbol("incomingKey"),y=Symbol("urlKey"),OZ=Symbol("headersKey"),A=Symbol("abortControllerKey"),HZ=Symbol("getAbortController"),T={get method(){return this[w].method||"GET"},get url(){return this[y]},get headers(){return this[OZ]||=zZ(this[w])},[HZ](){return this[_](),this[A]},[_](){return this[A]||=new AbortController,this[xZ]||=PZ(this.method,this[y],this.headers,this[w],this[A])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach((Z)=>{Object.defineProperty(T,Z,{get(){return this[_]()[Z]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach((Z)=>{Object.defineProperty(T,Z,{value:function(){return this[_]()[Z]()}})});Object.defineProperty(T,Symbol.for("nodejs.util.inspect.custom"),{value:function(Z,$,Q){let W={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[xZ]};return`Request (lightweight) ${Q(W,{...$,depth:Z==null?null:Z-1})}`}});Object.setPrototypeOf(T,N.prototype);var kZ=(Z,$)=>{let Q=Object.create(T);Q[w]=Z;let W=Z.url||"";if(W[0]!=="/"&&(W.startsWith("http://")||W.startsWith("https://"))){if(Z instanceof I)throw new V("Absolute URL for :path is not allowed in HTTP/2");try{let x=new URL(W);Q[y]=x.href}catch(x){throw new V("Invalid absolute URL",{cause:x})}return Q}let X=(Z instanceof I?Z.authority:Z.headers.host)||$;if(!X)throw new V("Missing host header");let Y;if(Z instanceof I){if(Y=Z.scheme,!(Y==="http"||Y==="https"))throw new V("Unsupported scheme")}else Y=Z.socket&&Z.socket.encrypted?"https":"http";let j=new URL(`${Y}://${X}${W}`);if(j.hostname.length!==X.length&&j.hostname!==X.replace(/:\d+$/,""))throw new V("Invalid host header");return Q[y]=j.href,Q},R=Symbol("responseCache"),f=Symbol("getResponseCache"),L=Symbol("cache"),p=global.Response,D=class Z{#$;#Z;[f](){return delete this[L],this[R]||=new p(this.#$,this.#Z)}constructor($,Q){let W;if(this.#$=$,Q instanceof Z){let X=Q[R];if(X){this.#Z=X,this[f]();return}else this.#Z=Q.#Z,W=new Headers(Q.#Z.headers)}else this.#Z=Q;if(typeof $==="string"||typeof $?.getReader<"u"||$ instanceof Blob||$ instanceof Uint8Array)this[L]=[Q?.status||200,$,W||Q?.headers]}get headers(){let $=this[L];if($){if(!($[2]instanceof Headers))$[2]=new Headers($[2]||{"content-type":"text/plain; charset=UTF-8"});return $[2]}return this[f]().headers}get status(){return this[L]?.[0]??this[f]().status}get ok(){let $=this.status;return $>=200&&$<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach((Z)=>{Object.defineProperty(D.prototype,Z,{get(){return this[f]()[Z]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach((Z)=>{Object.defineProperty(D.prototype,Z,{value:function(){return this[f]()[Z]()}})});Object.defineProperty(D.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(Z,$,Q){let W={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[R]};return`Response (lightweight) ${Q(W,{...$,depth:Z==null?null:Z-1})}`}});Object.setPrototypeOf(D,p);Object.setPrototypeOf(D.prototype,p.prototype);async function wZ(Z){return Promise.race([Z,Promise.resolve().then(()=>Promise.resolve(void 0))])}function GZ(Z,$,Q){let W=(x)=>{Z.cancel(x).catch(()=>{})};return $.on("close",W),$.on("error",W),(Q??Z.read()).then(j,X),Z.closed.finally(()=>{$.off("close",W),$.off("error",W)});function X(x){if(x)$.destroy(x)}function Y(){Z.read().then(j,X)}function j({done:x,value:B}){try{if(x)$.end();else if(!$.write(B))$.once("drain",Y);else return Z.read().then(j,X)}catch(K){X(K)}}}function yZ(Z,$){if(Z.locked)throw TypeError("ReadableStream is locked.");else if($.destroyed)return;return GZ(Z.getReader(),$)}var h=(Z)=>{let $={};if(!(Z instanceof Headers))Z=new Headers(Z??void 0);let Q=[];for(let[W,X]of Z)if(W==="set-cookie")Q.push(X);else $[W]=X;if(Q.length>0)$["set-cookie"]=Q;return $["content-type"]??="text/plain; charset=UTF-8",$},CZ="x-hono-already-sent";if(typeof global.crypto>"u")global.crypto=vZ;var u=Symbol("outgoingEnded"),XZ=Symbol("incomingDraining"),SZ=500,EZ=67108864,b=(Z)=>{let $=Z;if(Z.destroyed||$[XZ])return;if($[XZ]=!0,Z instanceof YZ){try{Z.stream?.close?.(DZ.NGHTTP2_NO_ERROR)}catch{}return}let Q=0,W=()=>{clearTimeout(Y),Z.off("data",j),Z.off("end",W),Z.off("error",W)},X=()=>{W();let x=Z.socket;if(x&&!x.destroyed)x.destroySoon()},Y=setTimeout(X,SZ);Y.unref?.();let j=(x)=>{if(Q+=x.length,Q>EZ)X()};Z.on("data",j),Z.on("end",W),Z.on("error",W),Z.resume()},IZ=()=>new Response(null,{status:400}),BZ=(Z)=>new Response(null,{status:Z instanceof Error&&(Z.name==="TimeoutError"||Z.constructor.name==="TimeoutError")?504:500}),q=(Z,$)=>{let Q=Z instanceof Error?Z:Error("unknown error",{cause:Z});if(Q.code==="ERR_STREAM_PREMATURE_CLOSE")console.info("The user aborted a request.");else{if(console.error(Z),!$.headersSent)$.writeHead(500,{"Content-Type":"text/plain"});$.end(`Error: ${Q.message}`),$.destroy(Q)}},KZ=(Z)=>{if("flushHeaders"in Z&&Z.writable)Z.flushHeaders()},FZ=async(Z,$)=>{let[Q,W,X]=Z[L],Y=!1;if(!X)X={"content-type":"text/plain; charset=UTF-8"};else if(X instanceof Headers)Y=X.has("content-length"),X=h(X);else if(Array.isArray(X)){let j=new Headers(X);Y=j.has("content-length"),X=h(j)}else for(let j in X)if(j.length===14&&j.toLowerCase()==="content-length"){Y=!0;break}if(!Y){if(typeof W==="string")X["Content-Length"]=Buffer.byteLength(W);else if(W instanceof Uint8Array)X["Content-Length"]=W.byteLength;else if(W instanceof Blob)X["Content-Length"]=W.size}if($.writeHead(Q,X),typeof W==="string"||W instanceof Uint8Array)$.end(W);else if(W instanceof Blob)$.end(new Uint8Array(await W.arrayBuffer()));else KZ($),await yZ(W,$)?.catch((j)=>q(j,$));$[u]?.()},bZ=(Z)=>typeof Z.then==="function",RZ=async(Z,$,Q={})=>{if(bZ(Z))if(Q.errorHandler)try{Z=await Z}catch(X){let Y=await Q.errorHandler(X);if(!Y)return;Z=Y}else Z=await Z.catch(BZ);if(L in Z)return FZ(Z,$);let W=h(Z.headers);if(Z.body){let X=Z.body.getReader(),Y=[],j=!1,x=void 0;if(W["transfer-encoding"]!=="chunked"){let B=2;for(let K=0;K<B;K++){x||=X.read();let M=await wZ(x).catch((U)=>{console.error(U),j=!0});if(!M){if(K===1){await new Promise((U)=>setTimeout(U)),B=3;continue}break}if(x=void 0,M.value)Y.push(M.value);if(M.done){j=!0;break}}if(j&&!("content-length"in W))W["content-length"]=Y.reduce((K,M)=>K+M.length,0)}if($.writeHead(Z.status,W),Y.forEach((B)=>{$.write(B)}),j)$.end();else{if(Y.length===0)KZ($);await GZ(X,$,x)}}else if(W[CZ]);else $.writeHead(Z.status,W),$.end();$[u]?.()},m=(Z,$={})=>{let Q=$.autoCleanupIncoming??!0;if($.overrideGlobalObjects!==!1&&global.Request!==N)Object.defineProperty(global,"Request",{value:N}),Object.defineProperty(global,"Response",{value:D});return async(W,X)=>{let Y,j;try{j=kZ(W,$.hostname);let x=!Q||W.method==="GET"||W.method==="HEAD";if(!x){if(W[jZ]=!0,W.on("end",()=>{x=!0}),W instanceof YZ)X[u]=()=>{if(!x)setTimeout(()=>{if(!x)setTimeout(()=>{b(W)})})};X.on("finish",()=>{if(!x)b(W)})}if(X.on("close",()=>{if(j[A]){if(W.errored)j[A].abort(W.errored.toString());else if(!X.writableFinished)j[A].abort("Client connection prematurely closed.")}if(!x)setTimeout(()=>{if(!x)setTimeout(()=>{b(W)})})}),Y=Z(j,{incoming:W,outgoing:X}),L in Y)return FZ(Y,X)}catch(x){if(!Y)if($.errorHandler){if(Y=await $.errorHandler(j?x:NZ(x)),!Y)return}else if(!j)Y=IZ();else Y=BZ(x);else return q(x,X)}try{return await RZ(Y,X,$)}catch(x){return q(x,X)}}};class d{constructor(Z={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=Z.sessionIdGenerator,this._enableJsonResponse=Z.enableJsonResponse??!1,this._eventStore=Z.eventStore,this._onsessioninitialized=Z.onsessioninitialized,this._onsessionclosed=Z.onsessionclosed,this._allowedHosts=Z.allowedHosts,this._allowedOrigins=Z.allowedOrigins,this._enableDnsRebindingProtection=Z.enableDnsRebindingProtection??!1,this._retryInterval=Z.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(Z,$,Q,W){let X={code:$,message:Q};if(W?.data!==void 0)X.data=W.data;return new Response(JSON.stringify({jsonrpc:"2.0",error:X,id:null}),{status:Z,headers:{"Content-Type":"application/json",...W?.headers}})}validateRequestHeaders(Z){if(!this._enableDnsRebindingProtection)return;if(this._allowedHosts&&this._allowedHosts.length>0){let $=Z.headers.get("host");if(!$||!this._allowedHosts.includes($)){let Q=`Invalid Host header: ${$}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let $=Z.headers.get("origin");if($&&!this._allowedOrigins.includes($)){let Q=`Invalid Origin header: ${$}`;return this.onerror?.(Error(Q)),this.createJsonErrorResponse(403,-32000,Q)}}return}async handleRequest(Z,$){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let Q=this.validateRequestHeaders(Z);if(Q)return Q;switch(Z.method){case"POST":return this.handlePostRequest(Z,$);case"GET":return this.handleGetRequest(Z);case"DELETE":return this.handleDeleteRequest(Z);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(Z,$,Q,W){if(!this._eventStore)return;if(W<"2025-11-25")return;let X=await this._eventStore.storeEvent(Q,{}),Y=`id: ${X}
2
+ data:
3
+
4
+ `;if(this._retryInterval!==void 0)Y=`id: ${X}
5
+ retry: ${this._retryInterval}
6
+ data:
7
+
8
+ `;Z.enqueue($.encode(Y))}async handleGetRequest(Z){if(!Z.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept text/event-stream");let Q=this.validateSession(Z);if(Q)return Q;let W=this.validateProtocolVersion(Z);if(W)return W;if(this._eventStore){let B=Z.headers.get("last-event-id");if(B)return this.replayEvents(B)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32000,"Conflict: Only one SSE stream is allowed per session");let X=new TextEncoder,Y,j=new ReadableStream({start:(B)=>{Y=B},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),x={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};if(this.sessionId!==void 0)x["mcp-session-id"]=this.sessionId;return this._streamMapping.set(this._standaloneSseStreamId,{controller:Y,encoder:X,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{Y.close()}catch{}}}),new Response(j,{headers:x})}async replayEvents(Z){if(!this._eventStore)return this.onerror?.(Error("Event store not configured")),this.createJsonErrorResponse(400,-32000,"Event store not configured");try{let $;if(this._eventStore.getStreamIdForEventId){if($=await this._eventStore.getStreamIdForEventId(Z),!$)return this.onerror?.(Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32000,"Invalid event ID format");if(this._streamMapping.get($)!==void 0)return this.onerror?.(Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32000,"Conflict: Stream already has an active connection")}let Q={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};if(this.sessionId!==void 0)Q["mcp-session-id"]=this.sessionId;let W=new TextEncoder,X,Y=new ReadableStream({start:(x)=>{X=x},cancel:()=>{}}),j=await this._eventStore.replayEventsAfter(Z,{send:async(x,B)=>{if(!this.writeSSEEvent(X,W,B,x)){this.onerror?.(Error("Failed replay events"));try{X.close()}catch{}}}});return this._streamMapping.set(j,{controller:X,encoder:W,cleanup:()=>{this._streamMapping.delete(j);try{X.close()}catch{}}}),new Response(Y,{headers:Q})}catch($){return this.onerror?.($),this.createJsonErrorResponse(500,-32000,"Error replaying events")}}writeSSEEvent(Z,$,Q,W){try{let X=`event: message
9
+ `;if(W)X+=`id: ${W}
10
+ `;return X+=`data: ${JSON.stringify(Q)}
11
+
12
+ `,Z.enqueue($.encode(X)),!0}catch(X){return this.onerror?.(X),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(Z,$){try{let Q=Z.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let W=Z.headers.get("content-type");if(!W||!W.includes("application/json"))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let X={headers:Object.fromEntries(Z.headers.entries()),url:new URL(Z.url)},Y;if($?.parsedBody!==void 0)Y=$.parsedBody;else try{Y=await Z.json()}catch{return this.onerror?.(Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let j;try{if(Array.isArray(Y))j=Y.map((F)=>c.parse(F));else j=[c.parse(Y)]}catch{return this.onerror?.(Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let x=j.some(l);if(x){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(j.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!x){let F=this.validateSession(Z);if(F)return F;let J=this.validateProtocolVersion(Z);if(J)return J}if(!j.some(z)){for(let F of j)this.onmessage?.(F,{authInfo:$?.authInfo,requestInfo:X});return new Response(null,{status:202})}let K=crypto.randomUUID(),M=j.find((F)=>l(F)),U=M?M.params.protocolVersion:Z.headers.get("mcp-protocol-version")??MZ;if(this._enableJsonResponse)return new Promise((F)=>{this._streamMapping.set(K,{resolveJson:F,cleanup:()=>{this._streamMapping.delete(K)}});for(let J of j)if(z(J))this._requestToStreamMapping.set(J.id,K);for(let J of j)this.onmessage?.(J,{authInfo:$?.authInfo,requestInfo:X})});let i=new TextEncoder,P,JZ=new ReadableStream({start:(F)=>{P=F},cancel:()=>{this._streamMapping.delete(K)}}),t={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)t["mcp-session-id"]=this.sessionId;for(let F of j)if(z(F))this._streamMapping.set(K,{controller:P,encoder:i,cleanup:()=>{this._streamMapping.delete(K);try{P.close()}catch{}}}),this._requestToStreamMapping.set(F.id,K);await this.writePrimingEvent(P,i,K,U);for(let F of j){let J,n;if(z(F)&&this._eventStore&&U>="2025-11-25")J=()=>{this.closeSSEStream(F.id)},n=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(F,{authInfo:$?.authInfo,requestInfo:X,closeSSEStream:J,closeStandaloneSSEStream:n})}return new Response(JZ,{status:200,headers:t})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(Z){let $=this.validateSession(Z);if($)return $;let Q=this.validateProtocolVersion(Z);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Z){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let $=Z.headers.get("mcp-session-id");if(!$)return this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if($!==this.sessionId)return this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Z){let $=Z.headers.get("mcp-protocol-version");if($!==null&&!C.includes($))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${$} (supported versions: ${C.join(", ")})`)),this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${$} (supported versions: ${C.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Z})=>{Z()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Z){let $=this._requestToStreamMapping.get(Z);if(!$)return;let Q=this._streamMapping.get($);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z)Z.cleanup()}async send(Z,$){let Q=$?.relatedRequestId;if(v(Z)||S(Z))Q=Z.id;if(Q===void 0){if(v(Z)||S(Z))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let Y;if(this._eventStore)Y=await this._eventStore.storeEvent(this._standaloneSseStreamId,Z);let j=this._streamMapping.get(this._standaloneSseStreamId);if(j===void 0)return;if(j.controller&&j.encoder)this.writeSSEEvent(j.controller,j.encoder,Z,Y);return}let W=this._requestToStreamMapping.get(Q);if(!W)throw Error(`No connection established for request ID: ${String(Q)}`);let X=this._streamMapping.get(W);if(!this._enableJsonResponse&&X?.controller&&X?.encoder){let Y;if(this._eventStore)Y=await this._eventStore.storeEvent(W,Z);this.writeSSEEvent(X.controller,X.encoder,Z,Y)}if(v(Z)||S(Z)){this._requestResponseMap.set(Q,Z);let Y=Array.from(this._requestToStreamMapping.entries()).filter(([x,B])=>B===W).map(([x])=>x);if(Y.every((x)=>this._requestResponseMap.has(x))){if(!X)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&X.resolveJson){let x={"Content-Type":"application/json"};if(this.sessionId!==void 0)x["mcp-session-id"]=this.sessionId;let B=Y.map((K)=>this._requestResponseMap.get(K));if(B.length===1)X.resolveJson(new Response(JSON.stringify(B[0]),{status:200,headers:x}));else X.resolveJson(new Response(JSON.stringify(B),{status:200,headers:x}))}else X.cleanup();for(let x of Y)this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x)}}}}class g{constructor(Z={}){this._requestContext=new WeakMap,this._webStandardTransport=new d(Z),this._requestListener=m(async($)=>{let Q=this._requestContext.get($);return this._webStandardTransport.handleRequest($,{authInfo:Q?.authInfo,parsedBody:Q?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(Z){this._webStandardTransport.onclose=Z}get onclose(){return this._webStandardTransport.onclose}set onerror(Z){this._webStandardTransport.onerror=Z}get onerror(){return this._webStandardTransport.onerror}set onmessage(Z){this._webStandardTransport.onmessage=Z}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(Z,$){return this._webStandardTransport.send(Z,$)}async handleRequest(Z,$,Q){let W=Z.auth;await m(async(Y)=>{return this._webStandardTransport.handleRequest(Y,{authInfo:W,parsedBody:Q})},{overrideGlobalObjects:!1})(Z,$)}closeSSEStream(Z){this._webStandardTransport.closeSSEStream(Z)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}var qZ=4194304,pZ={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version","Access-Control-Expose-Headers":"Mcp-Session-Id","Access-Control-Max-Age":"86400"};function uZ(Z){for(let[$,Q]of Object.entries(pZ))Z.setHeader($,Q)}function a(Z,$,Q){let W=JSON.stringify(Q);Z.writeHead($,{"Content-Type":"application/json"}),Z.end(W)}async function mZ(Z){let $=[],Q=0;for await(let W of Z){let X=W;if(Q+=X.byteLength,Q>qZ)throw Error("Request body too large");$.push(X)}if(Q===0)return;return JSON.parse(Buffer.concat($).toString("utf8"))}function cZ(Z={}){let $=Z.mcpPath??"/mcp",Q=Z.allowedHosts?.filter((Y)=>Y.length>0)??[],W=Q.length>0;return(Y,j)=>{X(Y,j).catch((x)=>{if(!j.headersSent)a(j,500,{jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null});else j.end();console.error("embd MCP HTTP handler error:",x)})};async function X(Y,j){if(uZ(j),Y.method==="OPTIONS"){j.writeHead(204).end();return}let x=new URL(Y.url??"/","http://localhost");if(x.pathname==="/"||x.pathname==="/health"){j.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}),j.end(`embd MCP server (stateless). POST ${$}
13
+ `);return}if(x.pathname!==$){a(j,404,{jsonrpc:"2.0",error:{code:-32601,message:`Not found. The MCP endpoint is ${$}.`},id:null});return}let B;if(Y.method==="POST")try{B=await mZ(Y)}catch{a(j,400,{jsonrpc:"2.0",error:{code:-32700,message:"Parse error: invalid or oversized JSON body"},id:null});return}let K=QZ(Z),M=new g({sessionIdGenerator:void 0,enableJsonResponse:!0,allowedHosts:Q,enableDnsRebindingProtection:W});j.on("close",()=>{M.close(),K.close()}),await K.connect(M),await M.handleRequest(Y,j,B)}}function B0(Z={}){return hZ(cZ(Z))}
14
+ export{LZ as a,UZ as b,fZ as c,AZ as d,QZ as e,cZ as f,B0 as g};