@lunora/mcp 1.0.0-alpha.24 → 1.0.0-alpha.240

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.
Files changed (36) hide show
  1. package/LICENSE.md +120 -0
  2. package/README.md +200 -14
  3. package/dist/bin.mjs +4 -47
  4. package/dist/docs/index.d.mts +258 -0
  5. package/dist/docs/index.d.ts +258 -0
  6. package/dist/docs/index.mjs +1 -0
  7. package/dist/index.d.mts +490 -26
  8. package/dist/index.d.ts +490 -26
  9. package/dist/index.mjs +1 -5
  10. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs +4 -0
  12. package/dist/packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs +3 -0
  14. package/dist/packem_shared/DOCS_SERVER_NAME-CUnLrk1a.mjs +1 -0
  15. package/dist/packem_shared/DOCS_URI_SCHEME-C35UQ5Fo.mjs +3 -0
  16. package/dist/packem_shared/LOCAL_SERVER_NAME-DM_NJ-eY.mjs +1 -0
  17. package/dist/packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-mO4JuHgV.mjs +1 -0
  18. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DA4wD25I.mjs +1 -0
  19. package/dist/packem_shared/connectStdio-n-RHjcwN.mjs +1 -0
  20. package/dist/packem_shared/createAuthedMcpFetchHandler-DSTZ2ftz.mjs +1 -0
  21. package/dist/packem_shared/createMcpFetchHandler-CNEfLA-N.mjs +1 -0
  22. package/dist/packem_shared/createPaidMcpServer-C_V1beyQ.mjs +1 -0
  23. package/dist/packem_shared/createToolServer-BtGuPyMU.mjs +1 -0
  24. package/dist/packem_shared/observability-tools-D4Z8dGS-.mjs +1 -0
  25. package/dist/packem_shared/promise-memo-OqVPWoUX.mjs +1 -0
  26. package/dist/packem_shared/serve-stateless.d-CKsbI0fP.d.mts +154 -0
  27. package/dist/packem_shared/serve-stateless.d-CKsbI0fP.d.ts +154 -0
  28. package/dist/packem_shared/toDocsSearchHits-CBLmtWXt.mjs +1 -0
  29. package/dist/packem_shared/tool-call-Bs-QeKp6.mjs +1 -0
  30. package/dist/packem_shared/tools-Dmnb3M2T.mjs +2 -0
  31. package/package.json +18 -5
  32. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-DWobae3P.mjs +0 -168
  33. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-CWb_wFd5.mjs +0 -204
  34. package/dist/packem_shared/connectStdio-bkJcaXYE.mjs +0 -76
  35. package/dist/packem_shared/createMcpFetchHandler-DfzBSLrm.mjs +0 -14
  36. package/dist/packem_shared/createPaidMcpServer-b-qp_aEF.mjs +0 -93
package/dist/index.d.ts CHANGED
@@ -1,83 +1,547 @@
1
1
  import { LunoraClient } from '@lunora/client';
2
+ import { T as ToolDefinition, f as ToolResult, e as ToolInputSchema, a as McpFetchHandler, b as McpTool } from "./packem_shared/serve-stateless.d-CKsbI0fP.js";
3
+ export { D as DEFAULT_MAX_REQUEST_BYTES, type d as McpServerInfo, type S as ServeStatelessOptions, g as createToolServer, s as serveStateless } from "./packem_shared/serve-stateless.d-CKsbI0fP.js";
2
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
- import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
4
- import { X402ChargeConfig, X402Price } from '@lunora/x402/charge';
5
5
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
6
- interface ToolInputSchema {
7
- properties: Record<string, unknown>;
8
- required?: ReadonlyArray<string>;
9
- type: "object";
10
- }
11
- interface ToolDefinition {
12
- description: string;
13
- inputSchema: ToolInputSchema;
14
- name: string;
15
- }
16
- interface ToolResult {
17
- content: {
18
- text: string;
19
- type: "text";
20
- }[];
21
- isError?: boolean;
22
- }
6
+ import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
7
+ /**
8
+ * The observability tools. Descriptions say WHEN to call the tool, not just
9
+ * what it returns — an agent picking between five similar reads needs the
10
+ * trigger, and it pays for these strings on every turn.
11
+ */
12
+ declare const OBSERVABILITY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
13
+ /** The read-only tool surface: introspection + query. Always exposed. */
23
14
  declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
15
+ /** The write tool surface (mutations + actions). Exposed ONLY when writes are enabled. */
24
16
  declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
25
- declare const toolDefinitions: (allowWrites: boolean) => ReadonlyArray<ToolDefinition>;
26
- declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean) => Promise<ToolResult>;
17
+ /**
18
+ * The tools this server advertises: every family whose gate is open, in table
19
+ * order. A gated family is OMITTED rather than refused — an AI agent can't
20
+ * invoke what it can't see — and {@link callTool} re-checks the same gate at
21
+ * dispatch, so the guarantee does not depend on a client honouring this list.
22
+ */
23
+ declare const toolDefinitions: (allowWrites: boolean, allowObservability?: boolean, allowDataReads?: boolean) => ReadonlyArray<ToolDefinition>;
24
+ /**
25
+ * Dispatch a tool call against `client`: find the family that owns `name`, check
26
+ * its gate, hand off. Unknown tools and thrown errors are returned as `isError`
27
+ * results (rather than rejections) so the calling model sees the failure as tool
28
+ * output, per the MCP convention.
29
+ *
30
+ * Each gate is enforced HERE as well as in {@link toolDefinitions}, so a call to
31
+ * a gated tool is refused even if the client somehow names one it was never
32
+ * shown.
33
+ */
34
+ declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean, allowObservability?: boolean, allowDataReads?: boolean) => Promise<ToolResult>;
35
+ /**
36
+ * Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
37
+ * MCP tool an external agent can call. The capability boundary is the MCP-server
38
+ * process + its token, so WHICH agents are exposed is config on the server (like
39
+ * `allowWrites`), not on `defineAgent` — keeping `@lunora/agent` codegen
40
+ * byte-identical.
41
+ */
27
42
  interface McpAgentExposure {
43
+ /** What the agent does — shown to the calling model, which decides from it. */
28
44
  description: string;
45
+ /** The agent's export name (its `ctx.agents.<name>` / `AGENT_<NAME>` binding). */
29
46
  name: string;
47
+ /** Override the model-facing tool name (default `agent_<name>`). */
30
48
  toolName?: string;
31
49
  }
50
+ /** The generic status/poll tool advertised alongside the per-agent tools. */
32
51
  declare const AGENT_STATUS_TOOL_NAME = "lunora_agent_status";
52
+ /**
53
+ * The uniform input schema every agent tool advertises. Agents share ONE run
54
+ * input (`@lunora/agent` has no per-agent validator), so there is nothing to
55
+ * derive per agent — a single static schema is reused for every agent tool.
56
+ */
33
57
  declare const AGENT_RUN_INPUT_SCHEMA: ToolInputSchema;
58
+ /**
59
+ * Parse `LUNORA_MCP_AGENTS` — a `;`-separated list of `name:description` pairs,
60
+ * e.g. `"support:Handles support questions;billing:Billing help"`. The
61
+ * description may itself contain colons (only the FIRST colon splits). Blank
62
+ * entries and entries with an empty name/description are skipped.
63
+ */
34
64
  declare const parseAgentsEnv: (raw: string | undefined) => McpAgentExposure[];
65
+ /**
66
+ * The tools this module advertises. Fail-closed: only the boolean `true` opts
67
+ * in (an env-plumbed caller could pass a truthy string), and the tools appear
68
+ * ONLY when at least one agent is exposed — so an agent-free or non-opted-in
69
+ * server never lists them.
70
+ */
35
71
  declare const agentToolDefinitions: (exposures: ReadonlyArray<McpAgentExposure>, allowAgents: boolean) => ReadonlyArray<ToolDefinition>;
72
+ /** Options threaded into a single agent tool dispatch. */
36
73
  interface CallAgentToolOptions {
74
+ /** Opt-in gate — must be exactly `true` or the call is refused fail-closed. */
37
75
  allowAgents: boolean;
76
+ /** The exposures advertised by this server. */
38
77
  exposures: ReadonlyArray<McpAgentExposure>;
78
+ /** Wall-clock budget a single call awaits before returning a pending result. */
39
79
  maxWaitMs?: number;
80
+ /** Delay between thread-status polls. */
40
81
  pollIntervalMs?: number;
82
+ /** Test seam replacing the between-poll wait; production uses a real timer. */
41
83
  wait?: (ms: number) => Promise<void>;
42
84
  }
85
+ /**
86
+ * Dispatch an agent tool call: start a durable run via `agents:agentRun`, then
87
+ * await-with-timeout — poll `agents:agentThread` until terminal (returning the
88
+ * final answer from `agents:agentMessages`) or, on budget exhaustion, return a
89
+ * NON-error pending payload the caller resumes with `lunora_agent_status`.
90
+ *
91
+ * Fail-closed: refused at dispatch unless `allowAgents === true`, mirroring the
92
+ * `allowWrites` guard — starting a run is a side effect and must not ride the
93
+ * read-only default.
94
+ */
43
95
  declare const callAgentTool: (client: LunoraClient, name: string, input: Record<string, unknown>, options: CallAgentToolOptions) => Promise<ToolResult>;
44
96
  interface LunoraMcpServerOptions {
97
+ /** Wall-clock budget a single agent tool call awaits before returning a pending result. */
45
98
  agentMaxWaitMs?: number;
99
+ /** Delay between agent thread-status polls. */
46
100
  agentPollIntervalMs?: number;
101
+ /** The agents this server fronts as MCP tools (see `allowAgents`). */
47
102
  agents?: ReadonlyArray<McpAgentExposure>;
103
+ /**
104
+ * Expose the per-agent tools (`agent_<name>` + the generic
105
+ * `lunora_agent_status`). Defaults to `false`, mirroring `allowWrites`:
106
+ * starting a durable agent run is a side effect, so the agent tools are
107
+ * omitted from the advertised list AND refused at dispatch unless explicitly
108
+ * opted in. Only takes effect together with a non-empty `agents` list.
109
+ */
48
110
  allowAgents?: boolean;
111
+ /**
112
+ * Expose `lunora_find_related`, which returns raw table rows read through the
113
+ * admin writer, so RLS policies and column masks do not apply. Defaults to
114
+ * `false`, for the same reason as `allowObservability`. Only takes effect
115
+ * when a `token` resolved. On the OAuth-protected path the verified token must
116
+ * also carry the data-read scope (see `DATA_READ_SCOPE` in `./tools`).
117
+ */
118
+ allowDataReads?: boolean;
119
+ /**
120
+ * Expose the observability tools (`lunora_get_logs`, `lunora_get_issues`,
121
+ * `lunora_get_advisories`, `lunora_get_query_insights`,
122
+ * `lunora_get_migration_status`). Defaults to `false`, mirroring
123
+ * `allowWrites`: they are read-only, but every row they return — log lines,
124
+ * request metadata, grouped error messages — is production user data that
125
+ * lands in the model's context and therefore at its provider. Holding the
126
+ * admin bearer is not consent to ship that, so it is a separate opt-in;
127
+ * without it the tools are omitted from the advertised list AND refused at
128
+ * dispatch. Only takes effect when a `token` resolved. On the OAuth-protected
129
+ * path the verified token must also carry the observability scope (see
130
+ * `OBSERVABILITY_SCOPE` in `./tools`); this option stays the outer gate.
131
+ */
132
+ allowObservability?: boolean;
133
+ /**
134
+ * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
135
+ * Defaults to `false`: the server is READ-ONLY unless explicitly opted in,
136
+ * so a prompt-injected or misaligned agent can't mutate the deployment with
137
+ * the configured token. When false the write tools are omitted from the
138
+ * advertised tool list AND refused at dispatch.
139
+ */
49
140
  allowWrites?: boolean;
141
+ /**
142
+ * Pre-built client (test injection). When omitted a `LunoraClient` is
143
+ * created from `url`/`token`/`fetch`.
144
+ */
50
145
  client?: LunoraClient;
146
+ /** `fetch` implementation; defaults to the ambient global. */
51
147
  fetch?: typeof fetch;
148
+ /**
149
+ * Bearer token sent on every RPC. **Required** alongside `url`, and it must
150
+ * be the deployment's **admin bearer**: the introspection/allowlist path
151
+ * every tool depends on (`lunora_list_functions`, `lunora_list_tables`, and
152
+ * the `assertRunnable` precheck that runs before every `run` tool) hits
153
+ * admin-gated `/_lunora/admin/*` routes, so no scoped/app token works
154
+ * today — it would 403 (`ADMIN_FORBIDDEN`) on the first tool call. The
155
+ * read-only guarantee is therefore NOT enforced by the token's scope; it is
156
+ * enforced in-process via `allowWrites: false` (the default), which omits
157
+ * the write tools from the advertised list and refuses them at dispatch.
158
+ *
159
+ * Because EVERY tool needs it, omitting it is a misconfiguration rather than
160
+ * a reduced-capability mode, and `createLunoraMcpServer` says so at
161
+ * construction instead of advertising a surface that 403s on first use. The
162
+ * one exception is the `client` injection seam (tests / a pre-authenticated
163
+ * client), where this server cannot know what the client can reach and so
164
+ * reads "unknown" fail-closed: the privileged observability tools stay
165
+ * unadvertised and are refused at dispatch.
166
+ */
52
167
  token?: string;
168
+ /** Base URL of the deployed Lunora Worker. Required unless `client` is given. */
53
169
  url?: string;
54
170
  }
171
+ /**
172
+ * Build an MCP `Server` whose tools talk to a Lunora deployment. The server is
173
+ * transport-agnostic — call `.connect(transport)` yourself, or use
174
+ * `connectStdio` for the common stdio case.
175
+ *
176
+ * Tool calls are dispatched through `callTool`, which the deployment reaches
177
+ * over HTTP RPC. No WebSocket is opened (the tools never subscribe), so this is
178
+ * safe to run as a short-lived stdio process.
179
+ */
55
180
  declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
181
+ /**
182
+ * Build the server and connect it over stdio — the transport MCP clients use
183
+ * when they spawn the `lunora-mcp` binary. Resolves once the transport is
184
+ * connected; the process then stays alive serving requests.
185
+ */
56
186
  declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
57
- type McpFetchHandler = (request: Request) => Promise<Response>;
58
- declare const createMcpFetchHandler: (options: LunoraMcpServerOptions) => McpFetchHandler;
187
+ /**
188
+ * The verified access-token payload better-auth hands a protected handler.
189
+ *
190
+ * A JWT payload is an open bag of claims, so this is deliberately an index
191
+ * signature with the two entries this module reads named. It is structurally
192
+ * satisfied by `jose`'s `JWTPayload`, which is what better-auth passes.
193
+ */
194
+ interface McpAccessTokenClaims {
195
+ readonly [claim: string]: unknown;
196
+ /** Space-delimited granted scopes (RFC 6749 §3.3). */
197
+ readonly scope?: unknown;
198
+ /** Subject — the user the token was issued for. */
199
+ readonly sub?: string;
200
+ }
201
+ /**
202
+ * The MCP auth gate: wraps a claims-aware handler into a plain fetch handler.
203
+ *
204
+ * Declared structurally here rather than imported from `@better-auth/mcp`,
205
+ * following the same rule `./paid` follows for `@lunora/x402`: a type import
206
+ * from a package this one does not depend on puts that package's `.d.ts` into
207
+ * the build graph, and a consumer that never installs it never builds it
208
+ * either — so the dts bundler looks for a `dist/` that does not exist and fails
209
+ * the build. Structural typing costs nothing here because this module never
210
+ * inspects the gate; it only applies it.
211
+ *
212
+ * Both better-auth entry points partially apply to this shape:
213
+ * `(handler) => requireMcpAuth(auth, handler, opts)` and
214
+ * `(handler) => createMcpProtectedRequestHandler(options, handler)`.
215
+ */
216
+ type McpAuthProtect = (handler: (request: Request, claims: McpAccessTokenClaims) => Promise<Response>) => McpFetchHandler;
217
+ /** Server options, or a function deriving them from the request's verified claims. */
218
+ type AuthedMcpServerOptions = ((claims: McpAccessTokenClaims) => LunoraMcpServerOptions | Promise<LunoraMcpServerOptions>) | LunoraMcpServerOptions;
219
+ interface AuthedMcpFetchHandlerOptions {
220
+ /**
221
+ * Largest accepted request body, in bytes — enforced while the body streams
222
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
223
+ * (128 KiB), which a value that is not a non-negative safe integer also
224
+ * falls back to.
225
+ */
226
+ maxRequestBytes?: number;
227
+ /**
228
+ * The OAuth gate to mount the MCP server behind. Pass
229
+ * `(handler) => requireMcpAuth(auth, handler, opts)` from
230
+ * `@lunora/auth/plugins`.
231
+ */
232
+ protect: McpAuthProtect;
233
+ /**
234
+ * The Lunora MCP server to serve once a request is authorized — either a
235
+ * fixed options object, or a function of the verified token claims so tool
236
+ * exposure can follow the scopes the token actually carries.
237
+ */
238
+ server: AuthedMcpServerOptions;
239
+ /**
240
+ * Step-up for the side-effecting tools: the write tools
241
+ * (`lunora_run_mutation` / `lunora_run_action`) and the agent tools (each
242
+ * `agent_<name>` and `lunora_agent_status`, since starting a durable run is a
243
+ * side effect). A token without `scope` still sees them in `tools/list`, and
244
+ * a `tools/call` to one throws `challenge([scope])` instead of running, so the
245
+ * client can re-authorize for the scope and retry. Unset, tools follow
246
+ * `allowWrites` / `allowAgents` alone. The raw-row and observability families
247
+ * need their own token scopes with or without `stepUp`; without it a call
248
+ * without the scope is refused as a tool error, not challenged.
249
+ */
250
+ stepUp?: {
251
+ /**
252
+ * Build the error that makes the gate answer 403 `insufficient_scope`
253
+ * naming `scopes`. Pass `createInsufficientScopeError` from
254
+ * `@lunora/auth/plugins`: better-auth only turns an error that factory
255
+ * created into the challenge.
256
+ */
257
+ challenge: (scopes: string[]) => unknown;
258
+ /** The scope a call to a side-effecting tool needs, e.g. `"lunora:write"`. */
259
+ scope: string;
260
+ };
261
+ }
262
+ /**
263
+ * Parse an access token's `scope` claim into a set.
264
+ *
265
+ * RFC 6749 §3.3 makes `scope` a space-delimited string, and better-auth issues
266
+ * it that way; anything else (absent, or a non-string an extension wrote)
267
+ * yields an empty set rather than throwing, so a scope check on a malformed
268
+ * token denies instead of crashing the tool call.
269
+ */
270
+ declare const mcpTokenScopes: (claims: McpAccessTokenClaims) => ReadonlySet<string>;
271
+ declare const createAuthedMcpFetchHandler: (options: AuthedMcpFetchHandlerOptions) => McpFetchHandler;
272
+ /** {@link createMcpFetchHandler} options: the server's, plus this transport's body limit. */
273
+ interface McpFetchHandlerOptions extends LunoraMcpServerOptions {
274
+ /**
275
+ * Largest accepted request body, in bytes — enforced while the body streams
276
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
277
+ * (128 KiB), which a value that is not a non-negative safe integer also
278
+ * falls back to.
279
+ */
280
+ maxRequestBytes?: number;
281
+ }
282
+ /**
283
+ * Build a stateless Streamable-HTTP fetch handler for a Lunora MCP server. Each
284
+ * invocation constructs a fresh proxy server and serves the request through
285
+ * {@link serveStateless}.
286
+ *
287
+ * The `LunoraClient` is resolved ONCE, here, and shared by every request: it is
288
+ * the same deployment on each one, and the public-function registry memo in
289
+ * `./tools` is keyed by client identity, so a per-request client would re-fetch
290
+ * that registry on every tool call. A misconfiguration (`url` without `token`)
291
+ * therefore throws when the handler is built rather than on first request,
292
+ * which is where `createLunoraMcpServer` already documents reporting it.
293
+ */
294
+ declare const createMcpFetchHandler: (options: McpFetchHandlerOptions) => McpFetchHandler;
295
+ /** A Lunora deployment the tools dispatch against. */
296
+ interface LocalDeployment {
297
+ token?: string;
298
+ url: string;
299
+ }
300
+ /**
301
+ * Where the deployment comes from: a fixed value, or a function consulted on
302
+ * every tool call.
303
+ *
304
+ * The resolver form exists because an editor spawns this server when the
305
+ * project opens — routinely *before* `lunora dev` is running, and it keeps the
306
+ * process alive across every restart afterwards. A URL captured once at startup
307
+ * would therefore be absent for the entire first session and stale after the
308
+ * first restart.
309
+ */
310
+ type LocalDeploymentSource = (() => LocalDeployment | undefined) | LocalDeployment;
311
+ interface LocalMcpServerOptions {
312
+ /**
313
+ * Expose the deployment write tools (`lunora_run_mutation` /
314
+ * `lunora_run_action`). Defaults to `false` — the same fail-closed default
315
+ * as the remote server. Locally the blast radius is dev data rather than
316
+ * production, but a mutation is still a side effect an agent should be
317
+ * granted deliberately.
318
+ */
319
+ allowWrites?: boolean;
320
+ /**
321
+ * The Lunora deployment (usually the running dev server) to expose. Omit to
322
+ * leave the deployment tools out entirely.
323
+ */
324
+ deployment?: LocalDeploymentSource;
325
+ /** Docs site origin backing the documentation tools; `false` omits them. */
326
+ docs?: false | {
327
+ baseUrl?: string;
328
+ };
329
+ /** Extra tools to compose in, e.g. the CLI's local dev-server tools. */
330
+ extraTools?: ReadonlyArray<McpTool>;
331
+ /** `fetch` implementation; defaults to the ambient global. */
332
+ fetch?: typeof fetch;
333
+ /** Version reported in the MCP handshake — the host CLI's, not this package's. */
334
+ version?: string;
335
+ }
336
+ /** Server identity advertised in the MCP `initialize` handshake. */
337
+ declare const LOCAL_SERVER_NAME = "lunora";
338
+ /** Shown when a deployment tool is called and no dev server can be found. */
339
+ declare const NO_DEPLOYMENT_MESSAGE = "no Lunora dev server is running for this project — start one with `lunora dev`, then call this tool again (call lunora_dev_status to check).";
340
+ /**
341
+ * Assemble the tool list, in the order it is advertised: docs first (the
342
+ * surface that always works), then the caller's extras, then the error catalog
343
+ * (compiled in, so it needs no deployment either), then the deployment tools.
344
+ * Order also decides precedence — `createToolServer` keeps the first
345
+ * registration of a duplicated name.
346
+ *
347
+ * `clientFor` is the shared client cache built once by
348
+ * {@link createLocalMcpServer} and threaded into both the tool and resource
349
+ * surfaces. Exported (and called directly by tests) without going through
350
+ * `createLocalMcpServer`, so a caller that omits it gets a private,
351
+ * call-scoped cache — same shape as before this surface was shared, just
352
+ * without the cross-surface sharing that only matters once a resource
353
+ * surface exists alongside it.
354
+ */
355
+ declare const localTools: (options: LocalMcpServerOptions, clientFor?: (deployment: LocalDeployment) => LunoraClient) => ReadonlyArray<McpTool>;
356
+ /** Build the composed local server without connecting a transport. */
357
+ declare const createLocalMcpServer: (options?: LocalMcpServerOptions) => Server;
358
+ /**
359
+ * Build the composed local server and connect it over stdio — the transport an
360
+ * MCP client uses when it spawns `lunora mcp serve`. Resolves once connected;
361
+ * the process then stays alive serving requests.
362
+ */
363
+ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Server>;
364
+ /** A tool handler: receives the call's `arguments` bag, returns an MCP tool result. */
365
+ /**
366
+ * The x402 vocabulary this module needs, declared here rather than imported.
367
+ *
368
+ * The x402 package is an optional peer, and a type import from its `charge`
369
+ * entry puts its `.d.ts` back into this package's build graph:
370
+ * a consumer that never installs x402 never builds it either, so the dts bundler
371
+ * looks for a `dist/` that does not exist and fails. That is not hypothetical —
372
+ * it broke the docs site build, which runs a filtered build over the docs app and its dependency closure
373
+ * and therefore never builds x402.
374
+ *
375
+ * Declaring them locally is safe because this module never *inspects* a charge
376
+ * config; it forwards it whole to `createChargeMiddleware`. The index signature
377
+ * keeps a real charge config assignable as x402 grows fields.
378
+ */
379
+ /** Mirrors x402's `X402Price` — a decimal string like `"$0.05"`, or a number. */
380
+ type X402Price = number | string;
381
+ /** Mirrors x402's charge config with the per-tool price omitted. */
382
+ interface X402ChargeSettings {
383
+ /** Network this resource settles on. */
384
+ readonly network: string;
385
+ /** Everything else x402 accepts, forwarded untouched. */
386
+ readonly [key: string]: unknown;
387
+ /** Payout wallet(s), per network family. */
388
+ readonly recipient: {
389
+ readonly evm?: string;
390
+ readonly svm?: string;
391
+ };
392
+ }
59
393
  type ToolHandler = (arguments_: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
394
+ /** Registration shape for a free tool. */
60
395
  interface RegisterToolOptions {
396
+ /** Optional MCP tool annotations (`readOnlyHint`, `title`, …). */
61
397
  annotations?: Tool["annotations"];
398
+ /** Human/model-facing description of what the tool does. */
62
399
  description: string;
400
+ /** JSON-Schema object describing the tool's arguments. */
63
401
  inputSchema: ToolInputSchema;
402
+ /** Unique tool name (the MCP `tools/call` `name`). */
64
403
  name: string;
65
404
  }
405
+ /** Registration shape for a paid tool: a {@link RegisterToolOptions} plus its USD price. */
66
406
  interface RegisterPaidToolOptions extends RegisterToolOptions {
407
+ /** USD price per call (e.g. `"$0.05"`), charged via x402 before dispatch. */
67
408
  price: X402Price;
68
409
  }
69
- type PaidMcpChargeConfig = Omit<X402ChargeConfig, "price">;
410
+ /** x402 settlement vocabulary shared by every paid tool (network, recipient, facilitator); price is per-tool. */
411
+ type PaidMcpChargeConfig = X402ChargeSettings;
412
+ /** Config for `createPaidMcpServer`. */
70
413
  interface PaidMcpServerConfig {
414
+ /** The worker-level x402 charge config; each paid tool supplies only its own `price`. */
71
415
  charge: PaidMcpChargeConfig;
416
+ /**
417
+ * Largest accepted request body, in bytes — enforced while the body streams
418
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
419
+ * (128 KiB), which a value that is not a non-negative safe integer also
420
+ * falls back to.
421
+ */
422
+ maxRequestBytes?: number;
423
+ /** Name/version advertised in the MCP `initialize` handshake. Defaults to `lunora-paid-mcp`. */
72
424
  serverInfo?: {
73
425
  name: string;
74
426
  version: string;
75
427
  };
76
428
  }
429
+ /**
430
+ * The Worker execution context, as this module reads it: only `waitUntil`, and
431
+ * structurally, so the package takes no `@cloudflare/workers-types` dependency.
432
+ */
433
+ interface PaidMcpExecutionContext {
434
+ waitUntil?: (promise: Promise<unknown>) => void;
435
+ }
436
+ /**
437
+ * The paid server's fetch handler.
438
+ *
439
+ * Unlike the free `McpFetchHandler` it takes the Worker's full
440
+ * `(request, env, ctx)` triple — the shape `export default { fetch }` is called
441
+ * with — because the x402 receipt sink NEEDS `ctx.waitUntil`: work that is
442
+ * neither awaited into the response nor registered with it is cancelled when the
443
+ * request ends, so an async `onReceipt` (inserting the settled payment into a
444
+ * durable table) frequently never runs while the money has already moved
445
+ * on-chain. `env` is accepted and ignored so the handler drops straight into the
446
+ * default export; both are optional, so a non-Workers caller may still invoke it
447
+ * with a bare `Request` (the middleware then simply sees no `waitUntil`).
448
+ */
449
+ type PaidMcpFetchHandler = (request: Request, env?: unknown, context?: PaidMcpExecutionContext) => Promise<Response>;
450
+ /** A paid MCP server: register free/paid tools, then serve over Streamable HTTP. */
77
451
  interface PaidMcpServer {
78
- readonly fetchHandler: McpFetchHandler;
452
+ /** The Streamable-HTTP fetch handler; gates each paid `tools/call` behind x402. */
453
+ readonly fetchHandler: PaidMcpFetchHandler;
454
+ /** Register a **paid** tool: its dispatch runs the x402 charge middleware first. */
79
455
  paidTool: (options: RegisterPaidToolOptions, handler: ToolHandler) => void;
456
+ /** Register a **free** tool (coexists with paid tools on the same server). */
80
457
  tool: (options: RegisterToolOptions, handler: ToolHandler) => void;
81
458
  }
459
+ /**
460
+ * Create a paid MCP server. Register free tools with `tool()` and priced tools
461
+ * with `paidTool()` (they coexist), then serve `fetchHandler` over HTTP.
462
+ *
463
+ * The server is **stateless**: `fetchHandler` builds a fresh `Server` per
464
+ * request (reading the live tool registry), so tools registered before the
465
+ * first request are all visible. Each priced tool memoises one initialised
466
+ * `ChargeMiddleware` (keyed by tool name, baking that tool's price and naming
467
+ * the tool as the challenge `resource`); a failed init is not cached, so a
468
+ * transient facilitator outage retries on the next call.
469
+ */
82
470
  declare const createPaidMcpServer: (config: PaidMcpServerConfig) => PaidMcpServer;
83
- export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, type CallAgentToolOptions, type LunoraMcpServerOptions, type McpAgentExposure, type McpFetchHandler, type PaidMcpChargeConfig, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolDefinition, type ToolHandler, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, agentToolDefinitions, callAgentTool, callTool, connectStdio, createLunoraMcpServer, createMcpFetchHandler, createPaidMcpServer, parseAgentsEnv, toolDefinitions };
471
+ export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, type AuthedMcpFetchHandlerOptions, type AuthedMcpServerOptions,
472
+ /**
473
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
474
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
475
+ * framework's *documentation* (credential-free, and safe to host publicly).
476
+ *
477
+ * The deployment server: It registers tools for introspecting a deployment
478
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
479
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
480
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
481
+ * `lunora_explain_error` — a credential-free read of the static error catalog
482
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
483
+ * exposes the deployment's observability reads (`lunora_get_logs`,
484
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
485
+ * `lunora_get_migration_status`) when `allowObservability` (or the
486
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
487
+ * production user data, so they are omitted entirely without it. The server is
488
+ * read-only by default — the write tools are exposed only when `allowWrites`
489
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
490
+ * allowlisted against the deployment's discovered public functions. Past that
491
+ * gate the two write tools run a two-step confirmation handshake: the first
492
+ * call writes nothing and returns the proposed action plus a self-verifying
493
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
494
+ * digest executes (see `./write-confirmation`). It can also
495
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
496
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
497
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
498
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
499
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
500
+ * Workers-ready `Request` → `Response` handler), or build a server
501
+ * programmatically with `createLunoraMcpServer` and connect any transport.
502
+ *
503
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
504
+ * carry the deployment's admin bearer — so for a public deployment use
505
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
506
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
507
+ * and can scope tool exposure to the access token's own scopes.
508
+ */
509
+ type CallAgentToolOptions, LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, type McpAccessTokenClaims,
510
+ /**
511
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
512
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
513
+ * framework's *documentation* (credential-free, and safe to host publicly).
514
+ *
515
+ * The deployment server: It registers tools for introspecting a deployment
516
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
517
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
518
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
519
+ * `lunora_explain_error` — a credential-free read of the static error catalog
520
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
521
+ * exposes the deployment's observability reads (`lunora_get_logs`,
522
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
523
+ * `lunora_get_migration_status`) when `allowObservability` (or the
524
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
525
+ * production user data, so they are omitted entirely without it. The server is
526
+ * read-only by default — the write tools are exposed only when `allowWrites`
527
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
528
+ * allowlisted against the deployment's discovered public functions. Past that
529
+ * gate the two write tools run a two-step confirmation handshake: the first
530
+ * call writes nothing and returns the proposed action plus a self-verifying
531
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
532
+ * digest executes (see `./write-confirmation`). It can also
533
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
534
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
535
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
536
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
537
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
538
+ * Workers-ready `Request` → `Response` handler), or build a server
539
+ * programmatically with `createLunoraMcpServer` and connect any transport.
540
+ *
541
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
542
+ * carry the deployment's admin bearer — so for a public deployment use
543
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
544
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
545
+ * and can scope tool exposure to the access token's own scopes.
546
+ */
547
+ type McpAgentExposure, type McpAuthProtect, type McpFetchHandler, type McpFetchHandlerOptions, type McpTool, NO_DEPLOYMENT_MESSAGE, OBSERVABILITY_TOOL_DEFINITIONS, type PaidMcpChargeConfig, type PaidMcpExecutionContext, type PaidMcpFetchHandler, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolDefinition, type ToolHandler, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, agentToolDefinitions, callAgentTool, callTool, connectLocalStdio, connectStdio, createAuthedMcpFetchHandler, createLocalMcpServer, createLunoraMcpServer, createMcpFetchHandler, createPaidMcpServer, localTools, mcpTokenScopes, parseAgentsEnv, toolDefinitions };
package/dist/index.mjs CHANGED
@@ -1,5 +1 @@
1
- export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, agentToolDefinitions, callAgentTool, parseAgentsEnv } from './packem_shared/AGENT_RUN_INPUT_SCHEMA-DWobae3P.mjs';
2
- export { createMcpFetchHandler } from './packem_shared/createMcpFetchHandler-DfzBSLrm.mjs';
3
- export { createPaidMcpServer } from './packem_shared/createPaidMcpServer-b-qp_aEF.mjs';
4
- export { connectStdio, createLunoraMcpServer } from './packem_shared/connectStdio-bkJcaXYE.mjs';
5
- export { READ_ONLY_TOOL_DEFINITIONS, WRITE_TOOL_DEFINITIONS, callTool, toolDefinitions } from './packem_shared/READ_ONLY_TOOL_DEFINITIONS-CWb_wFd5.mjs';
1
+ import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as c,callAgentTool as T,parseAgentsEnv as a}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{createAuthedMcpFetchHandler as S,mcpTokenScopes as _}from"./packem_shared/createAuthedMcpFetchHandler-DSTZ2ftz.mjs";import{createToolServer as l}from"./packem_shared/createToolServer-BtGuPyMU.mjs";import{createMcpFetchHandler as n}from"./packem_shared/createMcpFetchHandler-CNEfLA-N.mjs";import{LOCAL_SERVER_NAME as N,NO_DEPLOYMENT_MESSAGE as s,connectLocalStdio as I,createLocalMcpServer as L,localTools as f}from"./packem_shared/LOCAL_SERVER_NAME-DM_NJ-eY.mjs";import{createPaidMcpServer as M}from"./packem_shared/createPaidMcpServer-C_V1beyQ.mjs";import{connectStdio as i,createLunoraMcpServer as D}from"./packem_shared/connectStdio-n-RHjcwN.mjs";import{R as d,W as v,c as F,t as U}from"./packem_shared/tools-Dmnb3M2T.mjs";import{DEFAULT_MAX_REQUEST_BYTES as g,serveStateless as h}from"./packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{O as G}from"./packem_shared/observability-tools-D4Z8dGS-.mjs";export{r as AGENT_RUN_INPUT_SCHEMA,t as AGENT_STATUS_TOOL_NAME,g as DEFAULT_MAX_REQUEST_BYTES,N as LOCAL_SERVER_NAME,s as NO_DEPLOYMENT_MESSAGE,G as OBSERVABILITY_TOOL_DEFINITIONS,d as READ_ONLY_TOOL_DEFINITIONS,v as WRITE_TOOL_DEFINITIONS,c as agentToolDefinitions,T as callAgentTool,F as callTool,I as connectLocalStdio,i as connectStdio,S as createAuthedMcpFetchHandler,L as createLocalMcpServer,D as createLunoraMcpServer,n as createMcpFetchHandler,M as createPaidMcpServer,l as createToolServer,f as localTools,_ as mcpTokenScopes,a as parseAgentsEnv,h as serveStateless,U as toolDefinitions};
@@ -0,0 +1 @@
1
+ const b="agents:agentRun",T="agents:agentThread",H="agents:agentMessages",p="lunora_agent_status",_=new Set(["awaiting_input","cancelled","error","idle"]),O=6e4,x=600,P={properties:{prompt:{description:"The task or message for the agent.",type:"string"},threadKey:{description:"Reuse to continue a conversation; omit to start a new thread.",type:"string"},title:{description:"Optional thread title (first run only).",type:"string"}},required:["prompt"],type:"object"},U={properties:{threadKey:{description:"The thread key returned by an agent tool call.",type:"string"}},required:["threadKey"],type:"object"},g=t=>t.toolName??`agent_${t.name}`,C=t=>{if(t===void 0)return[];const n=[];for(const e of t.split(";")){const r=e.trim();if(r.length===0)continue;const o=r.indexOf(":");if(o<=0)continue;const a=r.slice(0,o).trim(),s=r.slice(o+1).trim();a.length===0||s.length===0||n.push({description:s,name:a})}return n},L={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},K=(t,n)=>n!==!0||t.length===0?[]:[...t.map(r=>({annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:`Run the ${r.name} agent (starts a durable run)`},description:`${r.description} Starts a durable agent run and returns its final answer.`,inputSchema:P,name:g(r)})),{annotations:{...L,title:"Check a durable agent run"},description:"Check the status of a durable agent run (and its answer if finished) by its threadKey.",inputSchema:U,name:p}],G=(t,n)=>t===p||n.some(e=>g(e)===t),R=()=>`mcp-${crypto.randomUUID()}`,d=t=>({__lunoraRef:t}),k=async t=>{await new Promise(n=>{setTimeout(n,t)})},c=t=>({content:[{text:JSON.stringify(t,void 0,2),type:"text"}]}),i=t=>({content:[{text:t,type:"text"}],isError:!0}),l=(t,n)=>{const e=t[n];return typeof e=="string"&&e.length>0?e:void 0},A=t=>{for(let n=t.length-1;n>=0;n-=1){const e=t[n],r=e?.toolCalls,o=Array.isArray(r)&&r.length>0;if(e?.role==="assistant"&&!o)return typeof e.content=="string"?e.content:""}return""},w=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",S=async(t,n,e,r)=>{const o=await t.query(d(H),{key:n});if(e==="error"){const a=r!==null&&typeof r=="object"?r.error:void 0;return c({error:typeof a=="string"?a:"the agent run failed",status:e,threadKey:n})}return c(e==="awaiting_input"?{hint:"This run is paused on a human-in-the-loop tool approval. Approve or reject it in the app that owns the agent; MCP cannot supply the input. Poll lunora_agent_status with this threadKey afterwards.",status:e,text:A(o),threadKey:n}:{status:e,text:A(o),threadKey:n})},I=async(t,n)=>{const e=l(n,"threadKey");if(e===void 0)return i('"threadKey" is required and must be a non-empty string');const r=await t.query(d(T),{key:e}),o=w(r);return _.has(o)?S(t,e,o,r):c({status:o==="unknown"?"running":o,threadKey:e})},q=async(t,n,e,r)=>{try{if(r.allowAgents!==!0)return i(`tool "${n}" is disabled: agent tools are off. Enable them with the LUNORA_MCP_ALLOW_AGENTS env var.`);if(n===p)return await I(t,e);const o=r.exposures.find(u=>g(u)===n);if(o===void 0)return i(`agent tool "${n}" is not exposed by this MCP server`);const a=l(e,"prompt");if(a===void 0)return i('"prompt" is required and must be a non-empty string');const s=l(e,"threadKey")??R(),h=l(e,"title"),{id:E}=await t.mutation(d(b),{agent:o.name,input:a,threadKey:s,...h===void 0?{}:{title:h}}),f=r.pollIntervalMs??x,N=r.maxWaitMs??O,v=r.wait??k,M=Math.max(1,Math.ceil(N/f));for(let u=0;u<M;u+=1){const y=await t.query(d(T),{key:s}),m=w(y);if(_.has(m))return await S(t,s,m,y);await v(f)}return c({hint:"call lunora_agent_status with this threadKey to poll for the answer",runId:E,status:"running",threadKey:s})}catch(o){const a=o instanceof Error?o.message:String(o);return i(a)}};export{P as AGENT_RUN_INPUT_SCHEMA,p as AGENT_STATUS_TOOL_NAME,K as agentToolDefinitions,q as callAgentTool,A as finalAnswer,G as isAgentToolName,C as parseAgentsEnv};
@@ -0,0 +1,4 @@
1
+ import{toDocsSearchHits as h}from"./toDocsSearchHits-CBLmtWXt.mjs";const f="https://lunora.sh",u=1e4,m=t=>t.endsWith("/")?t.slice(0,-1):t,p="\\",g=(t,n,i)=>{for(let s=i;s<t.length;s+=1)if(t[s]===n&&t[s-1]!==p)return s;return-1},d=t=>t.replaceAll(String.raw`\[`,"[").replaceAll(String.raw`\]`,"]").replaceAll(String.raw`\(`,"(").replaceAll(String.raw`\)`,")"),S=t=>{const n=t.trim();if(!n.startsWith("- ["))return;const i=n.lastIndexOf("](");if(i===-1)return;const s=g(n,")",i+2);if(s===-1)return;const o=d(n.slice(3,i).trim()),c=d(n.slice(i+2,s).trim());if(o.length===0||c.length===0)return;const e=n.slice(s+1).trim(),r=e.startsWith(":")?e.slice(1).trim():"";return r.length>0?{description:r,title:o,url:c}:{title:o,url:c}},x=t=>{if(!t.endsWith(")"))return t;const n=t.lastIndexOf(" (");if(n===-1)return t;const i=t.slice(n+2,-1);return i.startsWith("/")||i.startsWith("http")?t.slice(0,n).trim():t},y=(t,n)=>{for(const i of t.split(`
2
+ `)){if(i.startsWith("# "))return x(i.slice(2).trim());if(i.trim().length>0)break}return n},b=t=>{if(!t.startsWith("# "))return t;const n=t.indexOf(`
3
+ `);return n===-1?"":t.slice(n+1).trimStart()},A=(t={})=>{const n=m(t.baseUrl??f),i=t.fetch??globalThis.fetch,s=t.timeoutMs??u,o=async e=>{try{const r=await i(`${n}${e}`,{headers:{accept:"text/plain, application/json"},signal:AbortSignal.timeout(s)});return r.ok?{body:await r.text()}:{missing:!0}}catch(r){return{unreachable:r instanceof Error?r.message:String(r)}}},c=(e,r)=>{if("unreachable"in e)throw new Error(`could not reach the documentation site at ${n}${r}: ${e.unreachable}`);return"missing"in e?void 0:e.body};return{getPage:async e=>{const r=c(await o(`/llms.mdx${e}`),`/llms.mdx${e}`);if(!(r===void 0||r.trim().length===0))return{content:b(r),title:y(r,e),url:e}},listPages:async()=>{const e=c(await o("/llms.txt"),"/llms.txt");if(e===void 0)return[];const r=[];for(const l of e.split(`
4
+ `)){const a=S(l);a!==void 0&&r.push(a)}return r},search:async e=>{const r=`/api/search?query=${encodeURIComponent(e)}`,l=c(await o(r),r);if(l===void 0)return[];let a;try{a=JSON.parse(l)}catch{return[]}return Array.isArray(a)?h(a):[]}}};export{f as DEFAULT_DOCS_BASE_URL,A as createRemoteDocsIndex,S as parseIndexLine};
@@ -0,0 +1 @@
1
+ import{WebStandardStreamableHTTPServerTransport as y}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";const u=128*1024,p=e=>e!==void 0&&Number.isSafeInteger(e)&&e>=0?e:u,l=async(e,t)=>{if(!e.body)return"";const r=e.body.getReader(),s=new TextDecoder;let n=0,o="";for(;;){const{done:i,value:a}=await r.read();if(i)break;if(a){if(n+=a.byteLength,n>t){r.cancel().catch(()=>{});return}o+=s.decode(a,{stream:!0})}}return o+s.decode()},d=(e,t,r)=>Response.json({error:{code:t,message:r},id:null,jsonrpc:"2.0"},{status:e}),c=()=>d(400,-32600,"batched requests are not supported: send one JSON-RPC message per request"),f=async(e,t)=>{if(e.method!=="POST")return{parsedBody:void 0};const r=p(t),s={response:d(413,-32600,`request body exceeds ${String(r)} bytes`)},n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>r)return s;const o=await l(e,r);if(o===void 0)return s;try{return{parsedBody:JSON.parse(o)}}catch{return{response:d(400,-32700,"parse error: body is not valid JSON")}}},b=async(e,t)=>{if(e.method!=="POST")return{parsedBody:t?.parsedBody};if(t?.parsedBody!==void 0)return Array.isArray(t.parsedBody)?{response:c()}:{parsedBody:t.parsedBody};const r=await f(e,t?.maxRequestBytes);return"response"in r?r:Array.isArray(r.parsedBody)?{response:c()}:r},B=async(e,t,r)=>{const s=await b(t,r);if("response"in s)return s.response;const n=new y({enableJsonResponse:!0,sessionIdGenerator:void 0});try{return await e.connect(n),await n.handleRequest(t,{authInfo:r?.authInfo,parsedBody:s.parsedBody})}finally{n.close().catch(()=>{}),e.close().catch(()=>{})}};export{u as DEFAULT_MAX_REQUEST_BYTES,f as readScreenedBody,B as serveStateless};
@@ -0,0 +1,3 @@
1
+ const T=10,A=50,h="docs";const _={properties:{limit:{description:`Maximum hits to return (default ${String(10)}, max ${String(50)})`,type:"number"},query:{description:'Search terms, e.g. "shardBy" or "optimistic updates"',type:"string"}},required:["query"],type:"object"},m={properties:{url:{description:'Site-relative page URL from a search hit, e.g. "/docs/sharding"',type:"string"}},required:["url"],type:"object"},g={properties:{},type:"object"},s={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},u={annotations:{...s,title:"Search the Lunora documentation"},description:"Search the Lunora documentation and return matching pages and sections. Use this before writing Lunora code (schema, queries, mutations, actions, sharding, .global(), client hooks) so the answer reflects the framework's current API rather than a guess. Follow a hit with lunora_get_doc to read the full page.",inputSchema:_,name:"lunora_search_docs"},l={annotations:{...s,title:"Read a Lunora documentation page"},description:"Return one Lunora documentation page in full, as Markdown. Takes the `url` of a lunora_search_docs hit or a lunora_list_docs entry.",inputSchema:m,name:"lunora_get_doc"},d={annotations:{...s,title:"List the Lunora documentation pages"},description:"List every Lunora documentation page with its title and description. Prefer lunora_search_docs when you know what you're looking for.",inputSchema:g,name:"lunora_list_docs"},L=[u,l,d],r=n=>({content:[{text:JSON.stringify(n,void 0,2),type:"text"}]}),p=n=>({content:[{text:n,type:"text"}],isError:!0}),a=512,c=(n,t)=>{const e=n[t];if(typeof e!="string"||e.trim().length===0)throw new TypeError(`"${t}" is required and must be a non-empty string`);if(e.length>a)throw new RangeError(`"${t}" must be at most ${String(a)} characters`);return e.trim()},f=n=>{const t=typeof n=="string"?Number(n):n;return typeof t!="number"||!Number.isFinite(t)?10:Math.min(50,Math.max(1,Math.floor(t)))},S=(n,t)=>{let e;try{e=decodeURIComponent(n)}catch{throw new RangeError(`"url" contains a malformed percent-escape: ${t}`)}if(e.includes("%")||e.includes("\\"))throw new RangeError(`"url" must not contain ".." or encoded segments: ${t}`);for(const o of e.split("/"))if(o===".."||o===".")throw new RangeError(`"url" must not contain ".." or encoded segments: ${t}`)},E=n=>{let t=n.trim().replaceAll("\\","/");if(t.startsWith("http://")||t.startsWith("https://")){const e=t.slice(t.indexOf("//")+2),o=e.indexOf("/");t=o===-1?"/":e.slice(o)}for(const e of["?","#"]){const o=t.indexOf(e);o!==-1&&(t=t.slice(0,o))}for(;t.endsWith("/")&&t.length>1;)t=t.slice(0,-1);return t.startsWith("/")||(t=t.startsWith("docs/")?`/${t}`:`/${h}/${t}`),S(t,n),t},y=n=>[{definition:u,handle:async t=>{const e=c(t,"query"),o=f(t.limit),i=(await n.search(e)).slice(0,o);return i.length===0?r({hits:[],note:`no documentation matched "${e}" — try fewer or more general terms, or lunora_list_docs to browse`}):r({hits:i})}},{definition:l,handle:async t=>{const e=E(c(t,"url")),o=await n.getPage(e);return o===void 0?p(`documentation page not found: ${e}. Use lunora_search_docs or lunora_list_docs to find a valid url.`):{content:[{text:`# ${o.title} (${o.url})
2
+
3
+ ${o.content}`,type:"text"}]}}},{definition:d,handle:async()=>{const t=await n.listPages();return t.length>500?r({note:`showing the first ${String(500)} of ${String(t.length)} pages — use lunora_search_docs to find the rest`,pages:t.slice(0,500)}):r(t)}}];export{T as DEFAULT_SEARCH_LIMIT,L as DOCS_TOOL_DEFINITIONS,A as MAX_SEARCH_LIMIT,y as docsTools,E as normalizeDocUrl};
@@ -0,0 +1 @@
1
+ import{createToolServer as o}from"./createToolServer-BtGuPyMU.mjs";import{serveStateless as s}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{DEFAULT_MAX_REQUEST_BYTES as i}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{docsResources as t}from"./DOCS_URI_SCHEME-C35UQ5Fo.mjs";import{docsTools as c}from"./DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs";const m="lunora-docs",n=e=>({name:m,version:e??"0.0.0"}),a=e=>o(n(e.version),c(e.index),t(e.index)),v=e=>r=>s(a(e),r,{maxRequestBytes:e.maxRequestBytes});export{i as DEFAULT_MAX_REQUEST_BYTES,m as DOCS_SERVER_NAME,v as createDocsMcpFetchHandler,a as createDocsMcpServer};
@@ -0,0 +1,3 @@
1
+ import{normalizeDocUrl as s}from"./DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs";const e="lunora-docs:",n=t=>`${e}${t}`,c=t=>t.startsWith(e)?t.slice(e.length):void 0,d=t=>({list:async()=>(await t.listPages()).map(o=>({...o.description===void 0?{}:{description:o.description},mimeType:"text/markdown",name:o.title,uri:n(o.url)})),read:async i=>{const o=c(i);if(o===void 0)return;const r=await t.getPage(s(o));return r===void 0?void 0:{mimeType:"text/markdown",text:`# ${r.title} (${r.url})
2
+
3
+ ${r.content}`}}});export{e as DOCS_URI_SCHEME,d as docsResources,c as fromDocsUri,n as toDocsUri};
@@ -0,0 +1 @@
1
+ import{LunoraClient as f}from"@lunora/client";import{StdioServerTransport as m}from"@modelcontextprotocol/sdk/server/stdio.js";import{e as p}from"./promise-memo-OqVPWoUX.mjs";import{createToolServer as v}from"./createToolServer-BtGuPyMU.mjs";import{createRemoteDocsIndex as h}from"./DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs";import{docsResources as E}from"./DOCS_URI_SCHEME-C35UQ5Fo.mjs";import{docsTools as y}from"./DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs";import{E as R,b as O,t as T,d as _,c as S}from"./tools-Dmnb3M2T.mjs";const l=e=>e.docs===!1?void 0:h({...e.docs?.baseUrl===void 0?{}:{baseUrl:e.docs.baseUrl},...e.fetch===void 0?{}:{fetch:e.fetch}}),P="lunora",C="no Lunora dev server is running for this project — start one with `lunora dev`, then call this tool again (call lunora_dev_status to check).",g=8,d=e=>{const n=new Map;return t=>{const r=JSON.stringify([t.url,t.token??""]),c=n.get(r);if(c!==void 0)return c;const o=new f({fetch:e,url:t.url});return t.token!==void 0&&t.token.length>0&&o.setAuthToken(t.token),p(n,g),n.set(r,o),o}},i=e=>e?.token!==void 0&&e.token.length>0,A=(e,n,t)=>{const r=typeof e=="function"?e:()=>e;return T(n,i(r())).filter(c=>!_.has(c.name)).map(c=>({definition:c,handle:async o=>{const s=r();return s===void 0?{content:[{text:C,type:"text"}],isError:!0}:S(t(s),c.name,o,n,i(s))}}))},I=()=>R.map(e=>({definition:e,handle:n=>Promise.resolve(O(e.name,n))})),N="lunora-spec:openrpc",k="lunora-spec:openapi",a=[{description:"The deployment's generated OpenRPC 1.x document — every RPC function's path, kind, and argument schema in one read, instead of list_functions plus one get_function_schema call per function.",fetch:async e=>e.fetchOpenRpc(),name:"OpenRPC specification",uri:N},{description:"The deployment's generated OpenAPI 3.1 document.",fetch:async e=>e.fetchOpenApi(),name:"OpenAPI specification",uri:k}],w=(e,n)=>{const t=typeof e=="function"?e:()=>e,r=async c=>{const o=t();if(o!==void 0)try{return await c.fetch(n(o))}catch{return}};return{list:async()=>(await Promise.all(a.map(async o=>await r(o)===void 0?void 0:{description:o.description,mimeType:"application/json",name:o.name,uri:o.uri}))).filter(o=>o!==void 0),read:async c=>{const o=a.find(u=>u.uri===c);if(o===void 0)return;const s=await r(o);return s===void 0?void 0:{mimeType:"application/json",text:JSON.stringify(s,void 0,2)}}}},x=e=>({list:async()=>(await Promise.all(e.map(async t=>t.list()))).flat(),read:async n=>{for(const t of e){const r=await t.read(n);if(r!==void 0)return r}}}),L=(e,n)=>{const t=[],r=l(e);return r!==void 0&&t.push(...y(r)),t.push(...e.extraTools??[],...I()),e.deployment!==void 0&&t.push(...A(e.deployment,e.allowWrites??!1,n??d(e.fetch))),t},U=(e={})=>{const n=l(e),t=[];n!==void 0&&t.push(E(n));const r=d(e.fetch);return e.deployment!==void 0&&t.push(w(e.deployment,r)),v({name:P,version:e.version??"0.0.0"},L(e,r),t.length===0?void 0:x(t))},H=async(e={})=>{const n=U(e);return await n.connect(new m),n};export{P as LOCAL_SERVER_NAME,C as NO_DEPLOYMENT_MESSAGE,k as OPENAPI_RESOURCE_URI,N as OPENRPC_RESOURCE_URI,H as connectLocalStdio,U as createLocalMcpServer,L as localTools};