@lunora/mcp 1.0.0-alpha.14 → 1.0.0-alpha.140

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 (32) hide show
  1. package/LICENSE.md +126 -0
  2. package/README.md +229 -10
  3. package/dist/bin.mjs +4 -37
  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 +516 -16
  8. package/dist/index.d.ts +516 -16
  9. package/dist/index.mjs +1 -2
  10. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_DOCS_BASE_URL-CZ3fVsSc.mjs +4 -0
  12. package/dist/packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_SEARCH_LIMIT-BqSYN5vr.mjs +3 -0
  14. package/dist/packem_shared/DOCS_SERVER_NAME-BMeAWi5h.mjs +1 -0
  15. package/dist/packem_shared/DOCS_URI_SCHEME-Buo752CV.mjs +3 -0
  16. package/dist/packem_shared/LOCAL_SERVER_NAME-BbopFImI.mjs +1 -0
  17. package/dist/packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-mO4JuHgV.mjs +1 -0
  18. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DKcVAOe2.mjs +1 -0
  19. package/dist/packem_shared/connectStdio-CQI9JGJC.mjs +1 -0
  20. package/dist/packem_shared/createAuthedMcpFetchHandler-Mfw8jlOV.mjs +1 -0
  21. package/dist/packem_shared/createMcpFetchHandler-C5doZK5c.mjs +1 -0
  22. package/dist/packem_shared/createPaidMcpServer-Ba1gMM4Y.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/tools-D-JWERWj.mjs +2 -0
  30. package/package.json +17 -3
  31. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DV2VkuuU.mjs +0 -143
  32. package/dist/packem_shared/connectStdio-nl-Tt_T1.mjs +0 -65
package/dist/index.d.mts CHANGED
@@ -1,33 +1,533 @@
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.mjs";
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.mjs";
2
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
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. */
14
+ declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
15
+ /** The write tool surface (mutations + actions). Exposed ONLY when writes are enabled. */
16
+ declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
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
+ */
42
+ interface McpAgentExposure {
43
+ /** What the agent does — shown to the calling model, which decides from it. */
44
+ description: string;
45
+ /** The agent's export name (its `ctx.agents.<name>` / `AGENT_<NAME>` binding). */
46
+ name: string;
47
+ /** Override the model-facing tool name (default `agent_<name>`). */
48
+ toolName?: string;
49
+ }
50
+ /** The generic status/poll tool advertised alongside the per-agent tools. */
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
+ */
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
+ */
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
+ */
71
+ declare const agentToolDefinitions: (exposures: ReadonlyArray<McpAgentExposure>, allowAgents: boolean) => ReadonlyArray<ToolDefinition>;
72
+ /** Options threaded into a single agent tool dispatch. */
73
+ interface CallAgentToolOptions {
74
+ /** Opt-in gate — must be exactly `true` or the call is refused fail-closed. */
75
+ allowAgents: boolean;
76
+ /** The exposures advertised by this server. */
77
+ exposures: ReadonlyArray<McpAgentExposure>;
78
+ /** Wall-clock budget a single call awaits before returning a pending result. */
79
+ maxWaitMs?: number;
80
+ /** Delay between thread-status polls. */
81
+ pollIntervalMs?: number;
82
+ /** Test seam replacing the between-poll wait; production uses a real timer. */
83
+ wait?: (ms: number) => Promise<void>;
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
+ */
95
+ declare const callAgentTool: (client: LunoraClient, name: string, input: Record<string, unknown>, options: CallAgentToolOptions) => Promise<ToolResult>;
3
96
  interface LunoraMcpServerOptions {
97
+ /** Wall-clock budget a single agent tool call awaits before returning a pending result. */
98
+ agentMaxWaitMs?: number;
99
+ /** Delay between agent thread-status polls. */
100
+ agentPollIntervalMs?: number;
101
+ /** The agents this server fronts as MCP tools (see `allowAgents`). */
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
+ */
110
+ allowAgents?: boolean;
111
+ /**
112
+ * Expose the observability tools (`lunora_get_logs`, `lunora_get_issues`,
113
+ * `lunora_get_advisories`, `lunora_get_query_insights`,
114
+ * `lunora_get_migration_status`). Defaults to `false`, mirroring
115
+ * `allowWrites`: they are read-only, but every row they return — log lines,
116
+ * request metadata, grouped error messages — is production user data that
117
+ * lands in the model's context and therefore at its provider. Holding the
118
+ * admin bearer is not consent to ship that, so it is a separate opt-in;
119
+ * without it the tools are omitted from the advertised list AND refused at
120
+ * dispatch. Only takes effect when a `token` resolved.
121
+ */
122
+ allowDataReads?: boolean;
123
+ allowObservability?: boolean;
124
+ /**
125
+ * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
126
+ * Defaults to `false`: the server is READ-ONLY unless explicitly opted in,
127
+ * so a prompt-injected or misaligned agent can't mutate the deployment with
128
+ * the configured token. When false the write tools are omitted from the
129
+ * advertised tool list AND refused at dispatch.
130
+ */
4
131
  allowWrites?: boolean;
132
+ /**
133
+ * Pre-built client (test injection). When omitted a `LunoraClient` is
134
+ * created from `url`/`token`/`fetch`.
135
+ */
5
136
  client?: LunoraClient;
137
+ /** `fetch` implementation; defaults to the ambient global. */
6
138
  fetch?: typeof fetch;
139
+ /**
140
+ * Bearer token sent on every RPC. **Required** alongside `url`, and it must
141
+ * be the deployment's **admin bearer**: the introspection/allowlist path
142
+ * every tool depends on (`lunora_list_functions`, `lunora_list_tables`, and
143
+ * the `assertRunnable` precheck that runs before every `run` tool) hits
144
+ * admin-gated `/_lunora/admin/*` routes, so no scoped/app token works
145
+ * today — it would 403 (`ADMIN_FORBIDDEN`) on the first tool call. The
146
+ * read-only guarantee is therefore NOT enforced by the token's scope; it is
147
+ * enforced in-process via `allowWrites: false` (the default), which omits
148
+ * the write tools from the advertised list and refuses them at dispatch.
149
+ *
150
+ * Because EVERY tool needs it, omitting it is a misconfiguration rather than
151
+ * a reduced-capability mode, and `createLunoraMcpServer` says so at
152
+ * construction instead of advertising a surface that 403s on first use. The
153
+ * one exception is the `client` injection seam (tests / a pre-authenticated
154
+ * client), where this server cannot know what the client can reach and so
155
+ * reads "unknown" fail-closed: the privileged observability tools stay
156
+ * unadvertised and are refused at dispatch.
157
+ */
7
158
  token?: string;
159
+ /** Base URL of the deployed Lunora Worker. Required unless `client` is given. */
8
160
  url?: string;
9
161
  }
162
+ /**
163
+ * Build an MCP `Server` whose tools talk to a Lunora deployment. The server is
164
+ * transport-agnostic — call `.connect(transport)` yourself, or use
165
+ * `connectStdio` for the common stdio case.
166
+ *
167
+ * Tool calls are dispatched through `callTool`, which the deployment reaches
168
+ * over HTTP RPC. No WebSocket is opened (the tools never subscribe), so this is
169
+ * safe to run as a short-lived stdio process.
170
+ */
10
171
  declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
172
+ /**
173
+ * Build the server and connect it over stdio — the transport MCP clients use
174
+ * when they spawn the `lunora-mcp` binary. Resolves once the transport is
175
+ * connected; the process then stays alive serving requests.
176
+ */
11
177
  declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
12
- interface ToolInputSchema {
13
- properties: Record<string, unknown>;
14
- required?: ReadonlyArray<string>;
15
- type: "object";
178
+ /**
179
+ * The verified access-token payload better-auth hands a protected handler.
180
+ *
181
+ * A JWT payload is an open bag of claims, so this is deliberately an index
182
+ * signature with the two entries this module reads named. It is structurally
183
+ * satisfied by `jose`'s `JWTPayload`, which is what better-auth passes.
184
+ */
185
+ interface McpAccessTokenClaims {
186
+ readonly [claim: string]: unknown;
187
+ /** Space-delimited granted scopes (RFC 6749 §3.3). */
188
+ readonly scope?: unknown;
189
+ /** Subject — the user the token was issued for. */
190
+ readonly sub?: string;
191
+ }
192
+ /**
193
+ * The MCP auth gate: wraps a claims-aware handler into a plain fetch handler.
194
+ *
195
+ * Declared structurally here rather than imported from `@better-auth/mcp`,
196
+ * following the same rule `./paid` follows for `@lunora/x402`: a type import
197
+ * from a package this one does not depend on puts that package's `.d.ts` into
198
+ * the build graph, and a consumer that never installs it never builds it
199
+ * either — so the dts bundler looks for a `dist/` that does not exist and fails
200
+ * the build. Structural typing costs nothing here because this module never
201
+ * inspects the gate; it only applies it.
202
+ *
203
+ * Both better-auth entry points partially apply to this shape:
204
+ * `(handler) => requireMcpAuth(auth, handler, opts)` and
205
+ * `(handler) => createMcpProtectedRequestHandler(options, handler)`.
206
+ */
207
+ type McpAuthProtect = (handler: (request: Request, claims: McpAccessTokenClaims) => Promise<Response>) => McpFetchHandler;
208
+ /** Server options, or a function deriving them from the request's verified claims. */
209
+ type AuthedMcpServerOptions = ((claims: McpAccessTokenClaims) => LunoraMcpServerOptions | Promise<LunoraMcpServerOptions>) | LunoraMcpServerOptions;
210
+ interface AuthedMcpFetchHandlerOptions {
211
+ /**
212
+ * Largest accepted request body, in bytes — enforced while the body streams
213
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
214
+ * (128 KiB), which a value that is not a non-negative safe integer also
215
+ * falls back to.
216
+ */
217
+ maxRequestBytes?: number;
218
+ /**
219
+ * The OAuth gate to mount the MCP server behind. Pass
220
+ * `(handler) => requireMcpAuth(auth, handler, opts)` from
221
+ * `@lunora/auth/plugins`.
222
+ */
223
+ protect: McpAuthProtect;
224
+ /**
225
+ * The Lunora MCP server to serve once a request is authorized — either a
226
+ * fixed options object, or a function of the verified token claims so tool
227
+ * exposure can follow the scopes the token actually carries.
228
+ */
229
+ server: AuthedMcpServerOptions;
230
+ }
231
+ /**
232
+ * Parse an access token's `scope` claim into a set.
233
+ *
234
+ * RFC 6749 §3.3 makes `scope` a space-delimited string, and better-auth issues
235
+ * it that way; anything else (absent, or a non-string an extension wrote)
236
+ * yields an empty set rather than throwing, so a scope check on a malformed
237
+ * token denies instead of crashing the tool call.
238
+ */
239
+ declare const mcpTokenScopes: (claims: McpAccessTokenClaims) => ReadonlySet<string>;
240
+ /**
241
+ * Build an OAuth-protected stateless Streamable-HTTP fetch handler for a Lunora
242
+ * MCP server.
243
+ *
244
+ * Unauthenticated requests never reach the MCP server at all: `protect` answers
245
+ * them with the RFC 9728 `WWW-Authenticate` challenge that starts the client's
246
+ * authorization flow. An authorized request builds a fresh proxy server from
247
+ * `server` (resolved against the verified claims) and serves it through
248
+ * {@link serveStateless}, exactly as the unprotected `createMcpFetchHandler`
249
+ * does — the transport behaviour is identical, only the gate is new.
250
+ *
251
+ * A fixed `server` object names one deployment, so its `LunoraClient` is
252
+ * resolved once and shared: the public-function registry memo in `./tools` is
253
+ * keyed by client identity and never hits when each request builds its own. The
254
+ * `(claims) => …` form is per-request by construction — the claims decide which
255
+ * deployment and token to use — so it keeps a client per request.
256
+ */
257
+ declare const createAuthedMcpFetchHandler: (options: AuthedMcpFetchHandlerOptions) => McpFetchHandler;
258
+ /** {@link createMcpFetchHandler} options: the server's, plus this transport's body limit. */
259
+ interface McpFetchHandlerOptions extends LunoraMcpServerOptions {
260
+ /**
261
+ * Largest accepted request body, in bytes — enforced while the body streams
262
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
263
+ * (128 KiB), which a value that is not a non-negative safe integer also
264
+ * falls back to.
265
+ */
266
+ maxRequestBytes?: number;
267
+ }
268
+ /**
269
+ * Build a stateless Streamable-HTTP fetch handler for a Lunora MCP server. Each
270
+ * invocation constructs a fresh proxy server and serves the request through
271
+ * {@link serveStateless}.
272
+ *
273
+ * The `LunoraClient` is resolved ONCE, here, and shared by every request: it is
274
+ * the same deployment on each one, and the public-function registry memo in
275
+ * `./tools` is keyed by client identity, so a per-request client would re-fetch
276
+ * that registry on every tool call. A misconfiguration (`url` without `token`)
277
+ * therefore throws when the handler is built rather than on first request,
278
+ * which is where `createLunoraMcpServer` already documents reporting it.
279
+ */
280
+ declare const createMcpFetchHandler: (options: McpFetchHandlerOptions) => McpFetchHandler;
281
+ /** A Lunora deployment the tools dispatch against. */
282
+ interface LocalDeployment {
283
+ token?: string;
284
+ url: string;
16
285
  }
17
- interface ToolDefinition {
286
+ /**
287
+ * Where the deployment comes from: a fixed value, or a function consulted on
288
+ * every tool call.
289
+ *
290
+ * The resolver form exists because an editor spawns this server when the
291
+ * project opens — routinely *before* `lunora dev` is running, and it keeps the
292
+ * process alive across every restart afterwards. A URL captured once at startup
293
+ * would therefore be absent for the entire first session and stale after the
294
+ * first restart.
295
+ */
296
+ type LocalDeploymentSource = (() => LocalDeployment | undefined) | LocalDeployment;
297
+ interface LocalMcpServerOptions {
298
+ /**
299
+ * Expose the deployment write tools (`lunora_run_mutation` /
300
+ * `lunora_run_action`). Defaults to `false` — the same fail-closed default
301
+ * as the remote server. Locally the blast radius is dev data rather than
302
+ * production, but a mutation is still a side effect an agent should be
303
+ * granted deliberately.
304
+ */
305
+ allowWrites?: boolean;
306
+ /**
307
+ * The Lunora deployment (usually the running dev server) to expose. Omit to
308
+ * leave the deployment tools out entirely.
309
+ */
310
+ deployment?: LocalDeploymentSource;
311
+ /** Docs site origin backing the documentation tools; `false` omits them. */
312
+ docs?: false | {
313
+ baseUrl?: string;
314
+ };
315
+ /** Extra tools to compose in, e.g. the CLI's local dev-server tools. */
316
+ extraTools?: ReadonlyArray<McpTool>;
317
+ /** `fetch` implementation; defaults to the ambient global. */
318
+ fetch?: typeof fetch;
319
+ /** Version reported in the MCP handshake — the host CLI's, not this package's. */
320
+ version?: string;
321
+ }
322
+ /** Server identity advertised in the MCP `initialize` handshake. */
323
+ declare const LOCAL_SERVER_NAME = "lunora";
324
+ /** Shown when a deployment tool is called and no dev server can be found. */
325
+ 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).";
326
+ /**
327
+ * Assemble the tool list, in the order it is advertised: docs first (the
328
+ * surface that always works), then the caller's extras, then the error catalog
329
+ * (compiled in, so it needs no deployment either), then the deployment tools.
330
+ * Order also decides precedence — `createToolServer` keeps the first
331
+ * registration of a duplicated name.
332
+ *
333
+ * `clientFor` is the shared client cache built once by
334
+ * {@link createLocalMcpServer} and threaded into both the tool and resource
335
+ * surfaces. Exported (and called directly by tests) without going through
336
+ * `createLocalMcpServer`, so a caller that omits it gets a private,
337
+ * call-scoped cache — same shape as before this surface was shared, just
338
+ * without the cross-surface sharing that only matters once a resource
339
+ * surface exists alongside it.
340
+ */
341
+ declare const localTools: (options: LocalMcpServerOptions, clientFor?: (deployment: LocalDeployment) => LunoraClient) => ReadonlyArray<McpTool>;
342
+ /** Build the composed local server without connecting a transport. */
343
+ declare const createLocalMcpServer: (options?: LocalMcpServerOptions) => Server;
344
+ /**
345
+ * Build the composed local server and connect it over stdio — the transport an
346
+ * MCP client uses when it spawns `lunora mcp serve`. Resolves once connected;
347
+ * the process then stays alive serving requests.
348
+ */
349
+ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Server>;
350
+ /** A tool handler: receives the call's `arguments` bag, returns an MCP tool result. */
351
+ /**
352
+ * The x402 vocabulary this module needs, declared here rather than imported.
353
+ *
354
+ * The x402 package is an optional peer, and a type import from its `charge`
355
+ * entry puts its `.d.ts` back into this package's build graph:
356
+ * a consumer that never installs x402 never builds it either, so the dts bundler
357
+ * looks for a `dist/` that does not exist and fails. That is not hypothetical —
358
+ * it broke the docs site build, which runs a filtered build over the docs app and its dependency closure
359
+ * and therefore never builds x402.
360
+ *
361
+ * Declaring them locally is safe because this module never *inspects* a charge
362
+ * config; it forwards it whole to `createChargeMiddleware`. The index signature
363
+ * keeps a real charge config assignable as x402 grows fields.
364
+ */
365
+ /** Mirrors x402's `X402Price` — a decimal string like `"$0.05"`, or a number. */
366
+ type X402Price = number | string;
367
+ /** Mirrors x402's charge config with the per-tool price omitted. */
368
+ interface X402ChargeSettings {
369
+ /** Network this resource settles on. */
370
+ readonly network: string;
371
+ /** Everything else x402 accepts, forwarded untouched. */
372
+ readonly [key: string]: unknown;
373
+ /** Payout wallet(s), per network family. */
374
+ readonly recipient: {
375
+ readonly evm?: string;
376
+ readonly svm?: string;
377
+ };
378
+ }
379
+ type ToolHandler = (arguments_: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
380
+ /** Registration shape for a free tool. */
381
+ interface RegisterToolOptions {
382
+ /** Optional MCP tool annotations (`readOnlyHint`, `title`, …). */
383
+ annotations?: Tool["annotations"];
384
+ /** Human/model-facing description of what the tool does. */
18
385
  description: string;
386
+ /** JSON-Schema object describing the tool's arguments. */
19
387
  inputSchema: ToolInputSchema;
388
+ /** Unique tool name (the MCP `tools/call` `name`). */
20
389
  name: string;
21
390
  }
22
- interface ToolResult {
23
- content: {
24
- text: string;
25
- type: "text";
26
- }[];
27
- isError?: boolean;
391
+ /** Registration shape for a paid tool: a {@link RegisterToolOptions} plus its USD price. */
392
+ interface RegisterPaidToolOptions extends RegisterToolOptions {
393
+ /** USD price per call (e.g. `"$0.05"`), charged via x402 before dispatch. */
394
+ price: X402Price;
28
395
  }
29
- declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
30
- declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
31
- declare const toolDefinitions: (allowWrites: boolean) => ReadonlyArray<ToolDefinition>;
32
- declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean) => Promise<ToolResult>;
33
- export { type LunoraMcpServerOptions, READ_ONLY_TOOL_DEFINITIONS, type ToolDefinition, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, callTool, connectStdio, createLunoraMcpServer, toolDefinitions };
396
+ /** x402 settlement vocabulary shared by every paid tool (network, recipient, facilitator); price is per-tool. */
397
+ type PaidMcpChargeConfig = X402ChargeSettings;
398
+ /** Config for `createPaidMcpServer`. */
399
+ interface PaidMcpServerConfig {
400
+ /** The worker-level x402 charge config; each paid tool supplies only its own `price`. */
401
+ charge: PaidMcpChargeConfig;
402
+ /**
403
+ * Largest accepted request body, in bytes — enforced while the body streams
404
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
405
+ * (128 KiB), which a value that is not a non-negative safe integer also
406
+ * falls back to.
407
+ */
408
+ maxRequestBytes?: number;
409
+ /** Name/version advertised in the MCP `initialize` handshake. Defaults to `lunora-paid-mcp`. */
410
+ serverInfo?: {
411
+ name: string;
412
+ version: string;
413
+ };
414
+ }
415
+ /**
416
+ * The Worker execution context, as this module reads it: only `waitUntil`, and
417
+ * structurally, so the package takes no `@cloudflare/workers-types` dependency.
418
+ */
419
+ interface PaidMcpExecutionContext {
420
+ waitUntil?: (promise: Promise<unknown>) => void;
421
+ }
422
+ /**
423
+ * The paid server's fetch handler.
424
+ *
425
+ * Unlike the free `McpFetchHandler` it takes the Worker's full
426
+ * `(request, env, ctx)` triple — the shape `export default { fetch }` is called
427
+ * with — because the x402 receipt sink NEEDS `ctx.waitUntil`: work that is
428
+ * neither awaited into the response nor registered with it is cancelled when the
429
+ * request ends, so an async `onReceipt` (inserting the settled payment into a
430
+ * durable table) frequently never runs while the money has already moved
431
+ * on-chain. `env` is accepted and ignored so the handler drops straight into the
432
+ * default export; both are optional, so a non-Workers caller may still invoke it
433
+ * with a bare `Request` (the middleware then simply sees no `waitUntil`).
434
+ */
435
+ type PaidMcpFetchHandler = (request: Request, env?: unknown, context?: PaidMcpExecutionContext) => Promise<Response>;
436
+ /** A paid MCP server: register free/paid tools, then serve over Streamable HTTP. */
437
+ interface PaidMcpServer {
438
+ /** The Streamable-HTTP fetch handler; gates each paid `tools/call` behind x402. */
439
+ readonly fetchHandler: PaidMcpFetchHandler;
440
+ /** Register a **paid** tool: its dispatch runs the x402 charge middleware first. */
441
+ paidTool: (options: RegisterPaidToolOptions, handler: ToolHandler) => void;
442
+ /** Register a **free** tool (coexists with paid tools on the same server). */
443
+ tool: (options: RegisterToolOptions, handler: ToolHandler) => void;
444
+ }
445
+ /**
446
+ * Create a paid MCP server. Register free tools with `tool()` and priced tools
447
+ * with `paidTool()` (they coexist), then serve `fetchHandler` over HTTP.
448
+ *
449
+ * The server is **stateless**: `fetchHandler` builds a fresh `Server` per
450
+ * request (reading the live tool registry), so tools registered before the
451
+ * first request are all visible. Each priced tool memoises one initialised
452
+ * `ChargeMiddleware` (keyed by tool name, baking that tool's price and naming
453
+ * the tool as the challenge `resource`); a failed init is not cached, so a
454
+ * transient facilitator outage retries on the next call.
455
+ */
456
+ declare const createPaidMcpServer: (config: PaidMcpServerConfig) => PaidMcpServer;
457
+ export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, type AuthedMcpFetchHandlerOptions, type AuthedMcpServerOptions,
458
+ /**
459
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
460
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
461
+ * framework's *documentation* (credential-free, and safe to host publicly).
462
+ *
463
+ * The deployment server: It registers tools for introspecting a deployment
464
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
465
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
466
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
467
+ * `lunora_explain_error` — a credential-free read of the static error catalog
468
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
469
+ * exposes the deployment's observability reads (`lunora_get_logs`,
470
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
471
+ * `lunora_get_migration_status`) when `allowObservability` (or the
472
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
473
+ * production user data, so they are omitted entirely without it. The server is
474
+ * read-only by default — the write tools are exposed only when `allowWrites`
475
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
476
+ * allowlisted against the deployment's discovered public functions. Past that
477
+ * gate the two write tools run a two-step confirmation handshake: the first
478
+ * call writes nothing and returns the proposed action plus a self-verifying
479
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
480
+ * digest executes (see `./write-confirmation`). It can also
481
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
482
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
483
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
484
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
485
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
486
+ * Workers-ready `Request` → `Response` handler), or build a server
487
+ * programmatically with `createLunoraMcpServer` and connect any transport.
488
+ *
489
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
490
+ * carry the deployment's admin bearer — so for a public deployment use
491
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
492
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
493
+ * and can scope tool exposure to the access token's own scopes.
494
+ */
495
+ type CallAgentToolOptions, LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, type McpAccessTokenClaims,
496
+ /**
497
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
498
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
499
+ * framework's *documentation* (credential-free, and safe to host publicly).
500
+ *
501
+ * The deployment server: It registers tools for introspecting a deployment
502
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
503
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
504
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
505
+ * `lunora_explain_error` — a credential-free read of the static error catalog
506
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
507
+ * exposes the deployment's observability reads (`lunora_get_logs`,
508
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
509
+ * `lunora_get_migration_status`) when `allowObservability` (or the
510
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
511
+ * production user data, so they are omitted entirely without it. The server is
512
+ * read-only by default — the write tools are exposed only when `allowWrites`
513
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
514
+ * allowlisted against the deployment's discovered public functions. Past that
515
+ * gate the two write tools run a two-step confirmation handshake: the first
516
+ * call writes nothing and returns the proposed action plus a self-verifying
517
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
518
+ * digest executes (see `./write-confirmation`). It can also
519
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
520
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
521
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
522
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
523
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
524
+ * Workers-ready `Request` → `Response` handler), or build a server
525
+ * programmatically with `createLunoraMcpServer` and connect any transport.
526
+ *
527
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
528
+ * carry the deployment's admin bearer — so for a public deployment use
529
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
530
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
531
+ * and can scope tool exposure to the access token's own scopes.
532
+ */
533
+ 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 };