mcp-use 2.0.0-beta.28 → 2.0.0-beta.30

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.
@@ -214,7 +214,7 @@ function mountPlan(host, plan) {
214
214
  async function mountProxyConnection(host, connection) {
215
215
  if (host.isStarted()) {
216
216
  throw new Error(
217
- "Cannot call proxy() after the server has started: register upstream servers before listen()/getHandler()."
217
+ "Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch."
218
218
  );
219
219
  }
220
220
  const namespace = connection.info.server.name;
@@ -237,7 +237,7 @@ function toClientConfig(config) {
237
237
  async function mountProxyServers(host, servers) {
238
238
  if (host.isStarted()) {
239
239
  throw new Error(
240
- "Cannot call proxy() after the server has started: register upstream servers before listen()/getHandler()."
240
+ "Cannot call proxy() after the server has started: register upstream servers before listen()/server.fetch."
241
241
  );
242
242
  }
243
243
  const { MCPClient } = await loadProxyClient();
@@ -1,4 +1,5 @@
1
1
  import type { AuthInfo, HandlerResultTypeMap, RequestTypeMap, ResultTypeMap } from "@modelcontextprotocol/server";
2
+ import type { Context, Env, HonoRequest } from "hono";
2
3
  declare const MCP_MIDDLEWARE_METHODS: readonly ["tools/call", "tools/list", "resources/read", "resources/list", "prompts/get", "prompts/list"];
3
4
  /** MCP methods currently intercepted by {@link MCPServer.use}. */
4
5
  export type McpMiddlewareMethod = (typeof MCP_MIDDLEWARE_METHODS)[number];
@@ -49,9 +50,15 @@ export type McpMiddlewareResult<M extends McpMiddlewareMethod> = McpMiddlewareOp
49
50
  * @internal
50
51
  */
51
52
  export declare function withMcpMiddlewareParams<M extends McpMiddlewareMethod>(request: unknown, params: McpMiddlewareOperationMap[M]["params"]): RequestTypeMap[M];
52
- interface MiddlewareContextCommon {
53
- /** The originating HTTP request, when this operation is served over HTTP. */
54
- request?: Request;
53
+ type MiddlewareContextCommon<TEnv extends Env = Env> = Omit<Context<TEnv>, "req"> & {
54
+ /** Hono request for the originating HTTP exchange. */
55
+ request?: HonoRequest;
56
+ /**
57
+ * Deprecated v1-compatible alias for {@link MiddlewareContext.request}.
58
+ *
59
+ * @deprecated Use `request` instead.
60
+ */
61
+ req?: HonoRequest;
55
62
  /** Session info when the underlying transport provides a session ID. */
56
63
  session?: {
57
64
  sessionId: string;
@@ -60,19 +67,19 @@ interface MiddlewareContextCommon {
60
67
  auth?: AuthInfo;
61
68
  /** Shared state for middleware participating in this request. */
62
69
  state: Map<string, unknown>;
63
- }
70
+ };
64
71
  /**
65
72
  * Context passed to MCP middleware.
66
73
  *
67
74
  * The conditional form preserves the correlation between `method` and
68
75
  * `params` when more than one method is represented.
69
76
  */
70
- export type MiddlewareContext<M extends McpMiddlewareMethod = McpMiddlewareMethod> = M extends McpMiddlewareMethod ? MiddlewareContextCommon & {
77
+ export type MiddlewareContext<M extends McpMiddlewareMethod = McpMiddlewareMethod, TEnv extends Env = Env> = M extends McpMiddlewareMethod ? MiddlewareContextCommon<TEnv> & {
71
78
  method: M;
72
79
  params: McpMiddlewareOperationMap[M]["params"];
73
80
  } : never;
74
81
  /** Preferred explicit name for the method-correlated middleware context. */
75
- export type McpMiddlewareContext<M extends McpMiddlewareMethod = McpMiddlewareMethod> = MiddlewareContext<M>;
82
+ export type McpMiddlewareContext<M extends McpMiddlewareMethod = McpMiddlewareMethod, TEnv extends Env = Env> = MiddlewareContext<M, TEnv>;
76
83
  /** Context with narrowed params for `tools/call`. */
77
84
  export type ToolsCallMiddlewareContext = MiddlewareContext<"tools/call">;
78
85
  /** Context with narrowed params for `tools/list`. */
@@ -86,13 +93,13 @@ export type PromptsGetMiddlewareContext = MiddlewareContext<"prompts/get">;
86
93
  /** Context with narrowed params for `prompts/list`. */
87
94
  export type PromptsListMiddlewareContext = MiddlewareContext<"prompts/list">;
88
95
  /** Map retained for compatibility and convenient indexed lookup. */
89
- export type McpMiddlewarePatternMap = {
90
- [M in McpMiddlewareMethod]: MiddlewareContext<M>;
96
+ export type McpMiddlewarePatternMap<TEnv extends Env = Env> = {
97
+ [M in McpMiddlewareMethod]: MiddlewareContext<M, TEnv>;
91
98
  };
92
99
  /** Continue the middleware chain with the result type for method `M`. */
93
100
  export type McpMiddlewareNext<M extends McpMiddlewareMethod> = () => Promise<McpMiddlewareResult<M>>;
94
101
  /** Middleware for one exact MCP method. */
95
- export type McpExactMiddlewareFn<M extends McpMiddlewareMethod> = (ctx: MiddlewareContext<M>, next: McpMiddlewareNext<M>) => Promise<McpMiddlewareResult<M>>;
102
+ export type McpExactMiddlewareFn<M extends McpMiddlewareMethod, TEnv extends Env = Env> = (ctx: MiddlewareContext<M, TEnv>, next: McpMiddlewareNext<M>) => Promise<McpMiddlewareResult<M>>;
96
103
  /**
97
104
  * Type-preserving middleware over every wrapped MCP method.
98
105
  *
@@ -100,19 +107,19 @@ export type McpExactMiddlewareFn<M extends McpMiddlewareMethod> = (ctx: Middlewa
100
107
  * resolves after downstream middleware, and the composer propagates that
101
108
  * downstream result unchanged. It must call `next()` or throw.
102
109
  */
103
- export type McpMiddlewareFn<Methods extends McpMiddlewareMethod = McpMiddlewareMethod> = (ctx: MiddlewareContext<Methods>, next: () => Promise<void>) => Promise<void>;
110
+ export type McpMiddlewareFn<Methods extends McpMiddlewareMethod = McpMiddlewareMethod, TEnv extends Env = Env> = (ctx: MiddlewareContext<Methods, TEnv>, next: () => Promise<void>) => Promise<void>;
104
111
  /** Exact MCP middleware methods plus the global pass-through wildcard. */
105
112
  export type McpMiddlewarePatternBody = McpMiddlewareMethod | "*";
106
- /** Canonical `mcp:` patterns plus prefixless compatibility forms. */
107
- export type McpMiddlewarePattern = McpMiddlewarePatternBody | `mcp:${McpMiddlewarePatternBody}`;
113
+ /** Canonical `mcp:` middleware patterns. */
114
+ export type McpMiddlewarePattern = `mcp:${McpMiddlewarePatternBody}`;
108
115
  /** Observer patterns additionally support grouping related MCP methods. */
109
116
  export type McpEventPatternBody = McpMiddlewarePatternBody | "tools/*" | "resources/*" | "prompts/*";
110
- type McpEventBasePattern = McpEventPatternBody | `mcp:${McpEventPatternBody}`;
117
+ type McpEventBasePattern = `mcp:${McpEventPatternBody}`;
111
118
  type StripMcpPrefix<P extends string> = P extends `mcp:${infer Body}` ? Body : P;
112
119
  /** Methods selected by an MCP middleware or observer pattern. */
113
120
  export type McpMiddlewareMethodsForPattern<P extends string> = StripMcpPrefix<P> extends infer Body ? Body extends McpMiddlewareMethod ? Body : Body extends "tools/*" ? Extract<McpMiddlewareMethod, `tools/${string}`> : Body extends "resources/*" ? Extract<McpMiddlewareMethod, `resources/${string}`> : Body extends "prompts/*" ? Extract<McpMiddlewareMethod, `prompts/${string}`> : Body extends "*" ? McpMiddlewareMethod : never : never;
114
121
  /** Infer an exact or type-preserving wildcard handler from pattern `P`. */
115
- export type McpMiddlewareFnFor<P extends McpMiddlewarePattern> = StripMcpPrefix<P> extends infer Body ? Body extends McpMiddlewareMethod ? McpExactMiddlewareFn<Body> : McpMiddlewareFn<McpMiddlewareMethodsForPattern<P>> : never;
122
+ export type McpMiddlewareFnFor<P extends McpMiddlewarePattern, TEnv extends Env = Env> = StripMcpPrefix<P> extends infer Body ? Body extends McpMiddlewareMethod ? McpExactMiddlewareFn<Body, TEnv> : McpMiddlewareFn<McpMiddlewareMethodsForPattern<P>, TEnv> : never;
116
123
  /**
117
124
  * Type-erased middleware adapter stored after registration.
118
125
  *
@@ -131,27 +138,25 @@ export interface McpMiddlewareEntry {
131
138
  * implementation signature is the deliberate erasure boundary, like the
132
139
  * official SDK's `setRequestHandler` implementation.
133
140
  */
134
- export declare function createMcpMiddlewareEntry<P extends McpMiddlewarePattern>(pattern: P, handler: McpMiddlewareFnFor<P>): McpMiddlewareEntry;
141
+ export declare function createMcpMiddlewareEntry<P extends McpMiddlewarePattern, TEnv extends Env = Env>(pattern: P, handler: McpMiddlewareFnFor<P, TEnv>): McpMiddlewareEntry;
135
142
  /** Phase for MCP observer event listeners registered via `server.on()`. */
136
143
  export type McpEventPhase = "before" | "complete";
137
144
  /** Read-only observer context correlated by MCP method. */
138
- export type ReadonlyMiddlewareContext<M extends McpMiddlewareMethod = McpMiddlewareMethod> = M extends McpMiddlewareMethod ? Omit<MiddlewareContext<M>, "params" | "request" | "state"> & {
145
+ export type ReadonlyMiddlewareContext<M extends McpMiddlewareMethod = McpMiddlewareMethod, TEnv extends Env = Env> = M extends McpMiddlewareMethod ? Omit<MiddlewareContext<M, TEnv>, "params" | "state"> & {
139
146
  readonly params: Readonly<McpMiddlewareOperationMap[M]["params"]>;
140
- /** The originating HTTP request, when this operation is served over HTTP. */
141
- readonly request?: Request;
142
147
  readonly state: ReadonlyMap<string, unknown>;
143
148
  } : never;
144
149
  /** Read-only observer invoked before an MCP handler runs. */
145
- export type McpEventListenerFn<Methods extends McpMiddlewareMethod = McpMiddlewareMethod> = <M extends Methods>(ctx: ReadonlyMiddlewareContext<M>) => void;
150
+ export type McpEventListenerFn<Methods extends McpMiddlewareMethod = McpMiddlewareMethod, TEnv extends Env = Env> = <M extends Methods>(ctx: ReadonlyMiddlewareContext<M, TEnv>) => void;
146
151
  /** Read-only observer invoked after an MCP handler completes. */
147
- export type McpCompleteEventListenerFn<Methods extends McpMiddlewareMethod = McpMiddlewareMethod> = <M extends Methods>(ctx: ReadonlyMiddlewareContext<M>, result: McpMiddlewareResult<M>) => void;
148
- type McpExactEventListenerFn<M extends McpMiddlewareMethod> = (ctx: ReadonlyMiddlewareContext<M>) => void;
149
- type McpExactCompleteEventListenerFn<M extends McpMiddlewareMethod> = (ctx: ReadonlyMiddlewareContext<M>, result: McpMiddlewareResult<M>) => void;
152
+ export type McpCompleteEventListenerFn<Methods extends McpMiddlewareMethod = McpMiddlewareMethod, TEnv extends Env = Env> = <M extends Methods>(ctx: ReadonlyMiddlewareContext<M, TEnv>, result: McpMiddlewareResult<M>) => void;
153
+ type McpExactEventListenerFn<M extends McpMiddlewareMethod, TEnv extends Env = Env> = (ctx: ReadonlyMiddlewareContext<M, TEnv>) => void;
154
+ type McpExactCompleteEventListenerFn<M extends McpMiddlewareMethod, TEnv extends Env = Env> = (ctx: ReadonlyMiddlewareContext<M, TEnv>, result: McpMiddlewareResult<M>) => void;
150
155
  /** MCP observer pattern, optionally targeting the completion phase. */
151
156
  export type McpEventPattern = McpEventBasePattern | `${McpEventBasePattern}:complete`;
152
157
  type StripCompleteSuffix<P extends string> = P extends `${infer Body}:complete` ? Body : P;
153
158
  /** Infer a typed before/complete observer from event pattern `P`. */
154
- export type McpEventListenerFnFor<P extends McpEventPattern> = StripCompleteSuffix<StripMcpPrefix<P>> extends infer Body ? Body extends McpMiddlewareMethod ? P extends `${string}:complete` ? McpExactCompleteEventListenerFn<Body> : McpExactEventListenerFn<Body> : P extends `${string}:complete` ? McpCompleteEventListenerFn<McpMiddlewareMethodsForPattern<StripCompleteSuffix<P>>> : McpEventListenerFn<McpMiddlewareMethodsForPattern<StripCompleteSuffix<P>>> : never;
159
+ export type McpEventListenerFnFor<P extends McpEventPattern, TEnv extends Env = Env> = StripCompleteSuffix<StripMcpPrefix<P>> extends infer Body ? Body extends McpMiddlewareMethod ? P extends `${string}:complete` ? McpExactCompleteEventListenerFn<Body, TEnv> : McpExactEventListenerFn<Body, TEnv> : P extends `${string}:complete` ? McpCompleteEventListenerFn<McpMiddlewareMethodsForPattern<StripCompleteSuffix<P>>, TEnv> : McpEventListenerFn<McpMiddlewareMethodsForPattern<StripCompleteSuffix<P>>, TEnv> : never;
155
160
  /** Internal type-erased observer entry. @internal */
156
161
  export interface McpEventListenerEntry {
157
162
  pattern: string;
@@ -159,15 +164,15 @@ export interface McpEventListenerEntry {
159
164
  handler: (ctx: ReadonlyMiddlewareContext, result?: unknown) => void;
160
165
  }
161
166
  /** Adapt a public method-correlated observer for type-erased storage. */
162
- export declare function createMcpEventListenerEntry<P extends McpEventPattern>(pattern: P, handler: McpEventListenerFnFor<P>): McpEventListenerEntry;
167
+ export declare function createMcpEventListenerEntry<P extends McpEventPattern, TEnv extends Env = Env>(pattern: P, handler: McpEventListenerFnFor<P, TEnv>): McpEventListenerEntry;
163
168
  /** Test whether a registered middleware or observer pattern matches a method. */
164
169
  export declare function matchesPattern(pattern: string, method: string): boolean;
165
170
  /** Compose matching middleware in FIFO registration order. */
166
- export declare function composeMiddleware<M extends McpMiddlewareMethod>(entries: McpMiddlewareEntry[], method: M, innerFn: () => Promise<McpMiddlewareResult<M>>): (ctx: MiddlewareContext<M>) => Promise<McpMiddlewareResult<M>>;
171
+ export declare function composeMiddleware<M extends McpMiddlewareMethod, TEnv extends Env = Env>(entries: McpMiddlewareEntry[], method: M, innerFn: () => Promise<McpMiddlewareResult<M>>): (ctx: MiddlewareContext<M, TEnv>) => Promise<McpMiddlewareResult<M>>;
167
172
  /** Build a read-only snapshot of middleware context for observer events. */
168
- export declare function freezeMiddlewareContext<M extends McpMiddlewareMethod>(ctx: MiddlewareContext<M>): ReadonlyMiddlewareContext<M>;
173
+ export declare function freezeMiddlewareContext<M extends McpMiddlewareMethod, TEnv extends Env = Env>(ctx: MiddlewareContext<M, TEnv>): ReadonlyMiddlewareContext<M, TEnv>;
169
174
  /** Run before/complete observers around a method-correlated middleware chain. */
170
- export declare function runMcpOperation<M extends McpMiddlewareMethod>(middlewares: McpMiddlewareEntry[], events: McpEventListenerEntry[], method: M, ctx: MiddlewareContext<M>, innerFn: () => Promise<McpMiddlewareResult<M>>): Promise<McpMiddlewareResult<M>>;
175
+ export declare function runMcpOperation<M extends McpMiddlewareMethod, TEnv extends Env = Env>(middlewares: McpMiddlewareEntry[], events: McpEventListenerEntry[], method: M, ctx: MiddlewareContext<M, TEnv>, innerFn: () => Promise<McpMiddlewareResult<M>>): Promise<McpMiddlewareResult<M>>;
171
176
  /** Strip `mcp:` prefix and optional `:complete` suffix from event patterns. */
172
177
  export declare function parseMcpPattern(raw: string): {
173
178
  pattern: string;
@@ -50,7 +50,7 @@ function createNextHandler(server) {
50
50
  server.__primeViews(parseBuildManifest(raw, manifestPath), {
51
51
  projectRoot
52
52
  });
53
- return server.getHandler();
53
+ return async (request) => server.fetch(request);
54
54
  };
55
55
  const handle = async (request) => {
56
56
  handlerPromise ??= initialize();
@@ -8,7 +8,7 @@ import {
8
8
  oauthMetadataResponse,
9
9
  requireBearerAuth,
10
10
  verifyBearerToken
11
- } from "../chunk-26JBVQUY.js";
11
+ } from "../chunk-QKJJ6DWK.js";
12
12
  import {
13
13
  oauthCustomProvider
14
14
  } from "../chunk-YF5X7FYF.js";
package/dist/prompts.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { GetPromptResult, StandardSchemaWithJSON } from "@modelcontextprotocol/server";
1
+ import type { CallToolResult, GetPromptResult, StandardSchemaWithJSON } from "@modelcontextprotocol/server";
2
+ import type { Env } from "hono";
2
3
  import type { RequestContext } from "./context.js";
3
4
  /** Declares a prompt's identity and argument schema. First argument to {@link MCPServer.prompt}. */
4
5
  export interface PromptDefinition {
@@ -20,7 +21,10 @@ export type InferPromptInput<T> = T extends {
20
21
  schema: infer S extends StandardSchemaWithJSON;
21
22
  } ? StandardSchemaWithJSON.InferOutput<S> : Record<string, unknown>;
22
23
  /**
23
- * Prompt execution callback. Returns the SDK's raw {@link GetPromptResult}.
24
+ * Prompt execution callback. Prefer the SDK's raw {@link GetPromptResult}.
25
+ *
26
+ * Deprecated response helpers that return a {@link CallToolResult} are still
27
+ * accepted and converted at registration time.
24
28
  *
25
29
  * @example
26
30
  * ```ts
@@ -31,4 +35,4 @@ export type InferPromptInput<T> = T extends {
31
35
  * })
32
36
  * ```
33
37
  */
34
- export type PromptCallback<TInput = Record<string, unknown>, TUser = never, HasOAuth extends boolean = false> = (params: TInput, ctx: RequestContext<TUser, HasOAuth>) => GetPromptResult | Promise<GetPromptResult>;
38
+ export type PromptCallback<TInput = Record<string, unknown>, TUser = never, HasOAuth extends boolean = false, TEnv extends Env = Env> = (params: TInput, ctx: RequestContext<TUser, HasOAuth, TEnv>) => GetPromptResult | CallToolResult | Promise<GetPromptResult | CallToolResult>;
@@ -4,7 +4,8 @@ import { type CallToolSuccess } from "../types/result-types.js";
4
4
  export type { CallToolSuccess } from "../types/result-types.js";
5
5
  export { ToolError } from "../types/result-types.js";
6
6
  /**
7
- * Typed server-tool call handle returned by {@link useCallTool}.
7
+ * Typed server-tool call handle returned by {@link useCallTool} and
8
+ * {@link useDynamicTool}.
8
9
  *
9
10
  * @typeParam Args - Tool argument object type.
10
11
  * @typeParam Result - Expected `structuredContent` type for a successful result.
@@ -39,6 +40,15 @@ export interface CallToolHandle<Args, Result> {
39
40
  /** Whether a call is in flight. */
40
41
  isPending: boolean;
41
42
  }
43
+ type ToolNameParameter<Name extends string> = string extends keyof RegisteredTools ? Name : Name extends keyof RegisteredTools ? Name : `Tool "${Name}" is not exported from the server entry. Export the ToolRef returned by server.tool().`;
44
+ type RegisteredToolInput<Name extends string> = Name extends keyof RegisteredTools ? RegisteredTools[Name]["input"] : Record<string, unknown>;
45
+ type RegisteredToolOutput<Name extends string> = Name extends keyof RegisteredTools ? RegisteredTools[Name]["output"] : unknown;
46
+ /**
47
+ * Call a server tool using a {@link ToolRef} value (inline-JSX stretch path).
48
+ *
49
+ * @typeParam R - Tool ref carrying name, input, and output types.
50
+ */
51
+ export declare function useCallTool<R extends ToolRef<string, unknown, unknown>>(ref: R): CallToolHandle<R extends ToolRef<string, infer I, unknown> ? I : never, R extends ToolRef<string, unknown, infer O> ? O : never>;
42
52
  /**
43
53
  * Call a registered server tool from the view with inferred types.
44
54
  *
@@ -66,17 +76,25 @@ export interface CallToolHandle<Args, Result> {
66
76
  * }
67
77
  * ```
68
78
  */
69
- export declare function useCallTool<Name extends keyof RegisteredTools>(name: Name): CallToolHandle<RegisteredTools[Name]["input"], RegisteredTools[Name]["output"]>;
79
+ export declare function useCallTool<const Name extends string>(name: ToolNameParameter<Name>): CallToolHandle<RegisteredToolInput<Name>, RegisteredToolOutput<Name>>;
70
80
  /**
71
- * Call a server tool using a {@link ToolRef} value (inline-JSX stretch path).
81
+ * Call a tool whose registration cannot be represented by an exported
82
+ * {@link ToolRef}, such as a tool created from a loop, runtime configuration,
83
+ * or an OpenAPI document.
72
84
  *
73
- * @typeParam R - Tool ref carrying name, input, and output types.
74
- */
75
- export declare function useCallTool<R extends ToolRef<string, unknown, unknown>>(ref: R): CallToolHandle<R extends ToolRef<string, infer I, unknown> ? I : never, R extends ToolRef<string, unknown, infer O> ? O : never>;
76
- /**
77
- * Call a server tool with explicit argument/result types (escape hatch).
85
+ * Prefer {@link useCallTool} for statically declared tools. This explicit
86
+ * escape hatch requires callers to supply the contract because TypeScript
87
+ * cannot infer runtime-only registrations.
88
+ *
89
+ * @example
90
+ * ```tsx
91
+ * const lookup = useDynamicTool<{ id: string }, { value: string }>("lookup");
92
+ * const result = await lookup.callTool({ id: "item-1" });
93
+ * ```
78
94
  *
79
- * @typeParam Args - Explicit argument object type.
80
- * @typeParam Result - Explicit `structuredContent` type.
95
+ * @typeParam Args - Explicit tool argument object type.
96
+ * @typeParam Result - Expected `structuredContent` type for a successful result.
97
+ * @param name - Runtime-registered tool name.
98
+ * @returns A call handle using the explicitly supplied contract.
81
99
  */
82
- export declare function useCallTool<Args extends Record<string, unknown>, Result = unknown>(name: string): CallToolHandle<Args, Result>;
100
+ export declare function useDynamicTool<Args extends Record<string, unknown>, Result = unknown>(name: string): CallToolHandle<Args, Result>;
@@ -14,7 +14,7 @@ export { Image } from "./components/image.js";
14
14
  export { ModelContext, modelContext } from "./components/model-context.js";
15
15
  export { ThemeProvider } from "./components/theme-provider.js";
16
16
  export { ViewControls } from "./components/view-controls.js";
17
- export { useCallTool, type CallToolHandle } from "./hooks/use-call-tool.js";
17
+ export { useCallTool, useDynamicTool, type CallToolHandle, } from "./hooks/use-call-tool.js";
18
18
  export { useDisplayMode } from "./hooks/use-display-mode.js";
19
19
  export { useFiles } from "./hooks/use-files.js";
20
20
  export { useHostContext, type HostContextHandle, } from "./hooks/use-host-context.js";
@@ -1318,6 +1318,12 @@ function ViewControls({
1318
1318
  // src/react/hooks/use-call-tool.ts
1319
1319
  import { useCallback, useRef as useRef2, useState as useState3 } from "react";
1320
1320
  function useCallTool(nameOrRef) {
1321
+ return useToolCall(nameOrRef);
1322
+ }
1323
+ function useDynamicTool(name) {
1324
+ return useToolCall(name);
1325
+ }
1326
+ function useToolCall(nameOrRef) {
1321
1327
  const toolName = typeof nameOrRef === "string" ? nameOrRef : nameOrRef.name;
1322
1328
  const runtime = useViewRuntime();
1323
1329
  const [data, setData] = useState3(
@@ -1526,6 +1532,7 @@ export {
1526
1532
  toolResultText,
1527
1533
  useCallTool,
1528
1534
  useDisplayMode,
1535
+ useDynamicTool,
1529
1536
  useFiles,
1530
1537
  useHostContext,
1531
1538
  useOpenExternal,
@@ -4,7 +4,7 @@ export interface Register {
4
4
  }
5
5
  type RegisteredToolsModule = Register extends {
6
6
  tools: infer M;
7
- } ? M : Record<never, never>;
7
+ } ? M : undefined;
8
8
  type ToolsFromModule<M> = {
9
9
  [K in keyof M as M[K] extends ToolRef<infer N, any, any> ? N : never]: M[K] extends ToolRef<any, infer I, infer O> ? {
10
10
  input: I;
@@ -14,8 +14,16 @@ type ToolsFromModule<M> = {
14
14
  /**
15
15
  * Map of registered tool names to their inferred input/output types, derived
16
16
  * from exported {@link ToolRef} values in the augmented {@link Register} module.
17
+ *
18
+ * Projects without an `mcp-env.d.ts` registration retain a loose string map so
19
+ * existing non-scaffolded applications keep compiling. Once the module is
20
+ * registered, only exported tool refs are accepted by typed React hooks; an
21
+ * empty registered module therefore exposes no tool names.
17
22
  */
18
- export type RegisteredTools = ToolsFromModule<RegisteredToolsModule>;
23
+ export type RegisteredTools = RegisteredToolsModule extends undefined ? Record<string, {
24
+ input: Record<string, unknown>;
25
+ output: unknown;
26
+ }> : ToolsFromModule<RegisteredToolsModule>;
19
27
  /**
20
28
  * Recursive partial for streamed JSON: every field optional at every depth.
21
29
  *
@@ -1,4 +1,5 @@
1
- import type { Annotations, CompleteResourceTemplateCallback, MetaObject, ReadResourceResult } from "@modelcontextprotocol/server";
1
+ import type { Annotations, CallToolResult, CompleteResourceTemplateCallback, MetaObject, ReadResourceResult } from "@modelcontextprotocol/server";
2
+ import type { Env } from "hono";
2
3
  import type { RequestContext } from "./context.js";
3
4
  /** Declares a static resource at a fixed URI. First argument to {@link MCPServer.resource}. */
4
5
  export interface ResourceDefinition {
@@ -27,9 +28,12 @@ export interface ResourceDefinition {
27
28
  _meta?: MetaObject;
28
29
  }
29
30
  /**
30
- * Resource read callback. Returns the SDK's raw {@link ReadResourceResult};
31
+ * Resource read callback. Prefer the SDK's raw {@link ReadResourceResult};
31
32
  * each `contents` entry addresses itself with the read `uri`.
32
33
  *
34
+ * Deprecated response helpers that return a {@link CallToolResult} are still
35
+ * accepted and converted at registration time.
36
+ *
33
37
  * @example
34
38
  * ```ts
35
39
  * async (uri) => ({
@@ -37,7 +41,7 @@ export interface ResourceDefinition {
37
41
  * })
38
42
  * ```
39
43
  */
40
- export type ResourceCallback<TUser = never, HasOAuth extends boolean = false> = (uri: URL, ctx: RequestContext<TUser, HasOAuth>) => ReadResourceResult | Promise<ReadResourceResult>;
44
+ export type ResourceCallback<TUser = never, HasOAuth extends boolean = false, TEnv extends Env = Env> = (uri: URL, ctx: RequestContext<TUser, HasOAuth, TEnv>) => ReadResourceResult | CallToolResult | Promise<ReadResourceResult | CallToolResult>;
41
45
  /**
42
46
  * A resource-template variable completer accepted by
43
47
  * {@link MCPServer.resourceTemplate}.
@@ -115,6 +119,11 @@ export type InferTemplateParams<T> = T extends {
115
119
  } ? string extends U ? Record<string, TemplateVariableValue> : {
116
120
  [K in ExtractTemplateVariables<U>]: TemplateVariableValue;
117
121
  } : Record<string, TemplateVariableValue>;
118
- /** Resource template read callback; receives the matched URI and variables. */
119
- export type ResourceTemplateCallback<TParams = Record<string, TemplateVariableValue>, TUser = never, HasOAuth extends boolean = false> = (uri: URL, params: TParams, ctx: RequestContext<TUser, HasOAuth>) => ReadResourceResult | Promise<ReadResourceResult>;
122
+ /**
123
+ * Resource template read callback; receives the matched URI and variables.
124
+ *
125
+ * Prefer {@link ReadResourceResult}. Deprecated helper-shaped
126
+ * {@link CallToolResult} returns are still accepted and converted.
127
+ */
128
+ export type ResourceTemplateCallback<TParams = Record<string, TemplateVariableValue>, TUser = never, HasOAuth extends boolean = false, TEnv extends Env = Env> = (uri: URL, params: TParams, ctx: RequestContext<TUser, HasOAuth, TEnv>) => ReadResourceResult | CallToolResult | Promise<ReadResourceResult | CallToolResult>;
120
129
  export {};
@@ -0,0 +1,25 @@
1
+ import type { CallToolResult, GetPromptResult, ReadResourceResult } from "@modelcontextprotocol/server";
2
+ /**
3
+ * Convert a helper/`CallToolResult` (or pass through a raw resource result) to
4
+ * {@link ReadResourceResult}.
5
+ *
6
+ * Maps official {@link ContentBlock}s: `text` → text contents, `image`/`audio`
7
+ * `data` → `blob`, embedded `resource` → unwrap, `resource_link` skipped.
8
+ * Empty `content` with `structuredContent` becomes a JSON text entry.
9
+ *
10
+ * @param result - Tool-shaped or resource result from a resource callback.
11
+ * @param uri - URI of the resource being read (used for synthesized entries).
12
+ * @returns Official resource read envelope.
13
+ */
14
+ export declare function toResourceResult(result: CallToolResult | ReadResourceResult, uri: string): ReadResourceResult;
15
+ /**
16
+ * Convert a helper/`CallToolResult` (or pass through a raw prompt result) to
17
+ * {@link GetPromptResult}.
18
+ *
19
+ * Each tool {@link ContentBlock} becomes a `user` {@link PromptMessage}
20
+ * (prompt messages already accept the same content-block union).
21
+ *
22
+ * @param result - Tool-shaped or prompt result from a prompt callback.
23
+ * @returns Official prompt get envelope.
24
+ */
25
+ export declare function toPromptResult(result: CallToolResult | GetPromptResult): GetPromptResult;
@@ -0,0 +1,223 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/server";
2
+ /**
3
+ * Typed {@link CallToolResult} that constrains `structuredContent` to `T`.
4
+ *
5
+ * @deprecated Prefer returning a raw {@link CallToolResult} from tool
6
+ * callbacks. Example: `{ content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data }`.
7
+ *
8
+ * @typeParam T - Structured payload type (typically an object).
9
+ */
10
+ export interface TypedCallToolResult<T extends Record<string, unknown> = Record<string, unknown>> {
11
+ [x: string]: unknown;
12
+ content: CallToolResult["content"];
13
+ isError?: CallToolResult["isError"];
14
+ _meta?: CallToolResult["_meta"];
15
+ structuredContent?: T;
16
+ }
17
+ /**
18
+ * Content-only tool result (`structuredContent` pinned to `never`).
19
+ *
20
+ * @deprecated Prefer returning a raw {@link CallToolResult}:
21
+ * `{ content: [{ type: "text", text }] }`.
22
+ */
23
+ export interface ToolContentResult {
24
+ [x: string]: unknown;
25
+ content: CallToolResult["content"];
26
+ isError?: CallToolResult["isError"];
27
+ _meta?: CallToolResult["_meta"];
28
+ structuredContent?: never;
29
+ }
30
+ /**
31
+ * Create a plain-text tool result.
32
+ *
33
+ * @deprecated Prefer `{ content: [{ type: "text", text: content }] }`.
34
+ *
35
+ * @param content - Text to return.
36
+ * @returns Tool result with a single text content block.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * // Preferred:
41
+ * return { content: [{ type: "text", text: `Hello, ${name}!` }] };
42
+ * // Deprecated:
43
+ * return text(`Hello, ${name}!`);
44
+ * ```
45
+ */
46
+ export declare function text(content: string): ToolContentResult;
47
+ /**
48
+ * Create a Markdown text tool result.
49
+ *
50
+ * @deprecated Prefer `{ content: [{ type: "text", text: content }] }`.
51
+ *
52
+ * @param content - Markdown text.
53
+ * @returns Tool result with `text/markdown` MIME metadata.
54
+ */
55
+ export declare function markdown(content: string): ToolContentResult;
56
+ /**
57
+ * Create an HTML text tool result.
58
+ *
59
+ * @deprecated Prefer `{ content: [{ type: "text", text: content }] }`.
60
+ *
61
+ * @param content - HTML text.
62
+ * @returns Tool result with `text/html` MIME metadata.
63
+ */
64
+ export declare function html(content: string): ToolContentResult;
65
+ /**
66
+ * Create an XML text tool result.
67
+ *
68
+ * @deprecated Prefer `{ content: [{ type: "text", text: content }] }`.
69
+ *
70
+ * @param content - XML text.
71
+ * @returns Tool result with `text/xml` MIME metadata.
72
+ */
73
+ export declare function xml(content: string): ToolContentResult;
74
+ /**
75
+ * Create a CSS text tool result.
76
+ *
77
+ * @deprecated Prefer `{ content: [{ type: "text", text: content }] }`.
78
+ *
79
+ * @param content - CSS text.
80
+ * @returns Tool result with `text/css` MIME metadata.
81
+ */
82
+ export declare function css(content: string): ToolContentResult;
83
+ /**
84
+ * Create a JavaScript text tool result.
85
+ *
86
+ * @deprecated Prefer `{ content: [{ type: "text", text: content }] }`.
87
+ *
88
+ * @param content - JavaScript source text.
89
+ * @returns Tool result with `text/javascript` MIME metadata.
90
+ */
91
+ export declare function javascript(content: string): ToolContentResult;
92
+ /**
93
+ * Create an image content tool result.
94
+ *
95
+ * @deprecated Prefer
96
+ * `{ content: [{ type: "image", data, mimeType }] }`.
97
+ *
98
+ * @param data - Base64 image data (or data URL payload).
99
+ * @param mimeType - Image MIME type.
100
+ * @returns Tool result with an image content block.
101
+ *
102
+ * @defaultValue mimeType - `"image/png"`
103
+ */
104
+ export declare function image(data: string, mimeType?: string): ToolContentResult;
105
+ /**
106
+ * Create an audio content tool result from base64 data.
107
+ *
108
+ * @deprecated Prefer
109
+ * `{ content: [{ type: "audio", data, mimeType }] }`.
110
+ *
111
+ * @param data - Base64-encoded audio.
112
+ * @param mimeType - Audio MIME type.
113
+ * @returns Tool result with an audio content block.
114
+ *
115
+ * @defaultValue mimeType - `"audio/wav"`
116
+ */
117
+ export declare function audio(data: string, mimeType?: string): ToolContentResult;
118
+ /**
119
+ * Create a binary payload carried as base64 text.
120
+ *
121
+ * @deprecated Prefer a raw {@link CallToolResult} with an appropriate content
122
+ * block, or a resource `{ contents: [{ uri, mimeType, blob }] }`.
123
+ *
124
+ * @param base64Data - Base64-encoded bytes.
125
+ * @param mimeType - MIME type of the binary payload.
126
+ * @returns Tool result with base64 text and binary MIME metadata.
127
+ */
128
+ export declare function binary(base64Data: string, mimeType: string): ToolContentResult;
129
+ /**
130
+ * Create an embedded-resource content block for a tool result.
131
+ *
132
+ * Supports `resource(uri, mimeType, text?)` or `resource(uri, callToolResult)`.
133
+ *
134
+ * @deprecated Prefer
135
+ * `{ content: [{ type: "resource", resource: { uri, mimeType, text } }] }`.
136
+ *
137
+ * @param uri - Resource URI.
138
+ * @param mimeTypeOrContent - MIME type string, or a helper/`CallToolResult` to extract from.
139
+ * @param text - Optional text body (3-arg form).
140
+ * @returns Tool result with an embedded resource content block.
141
+ */
142
+ export declare function resource(uri: string, mimeTypeOrContent: string | CallToolResult | TypedCallToolResult, text?: string): ToolContentResult;
143
+ /**
144
+ * Create a failed tool result.
145
+ *
146
+ * @deprecated Prefer
147
+ * `{ isError: true, content: [{ type: "text", text: message }] }`.
148
+ *
149
+ * @param message - Error message shown to the model.
150
+ * @returns Tool result with `isError: true`.
151
+ */
152
+ export declare function error(message: string): TypedCallToolResult<never>;
153
+ /**
154
+ * Create a structured JSON object tool result.
155
+ *
156
+ * @deprecated Prefer
157
+ * `{ content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data }`.
158
+ *
159
+ * @typeParam T - Object payload type.
160
+ * @param data - Object (or array — forwarded to {@link array}) to return.
161
+ * @returns Tool result with JSON text and `structuredContent`.
162
+ */
163
+ export declare function object<T extends Record<string, unknown>>(data: T): TypedCallToolResult<T>;
164
+ /**
165
+ * Create a structured array tool result (2026 any-JSON root — no `{ data }` wrap).
166
+ *
167
+ * @deprecated Prefer
168
+ * `{ content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data }`
169
+ * or `{ content: [], structuredContent: data }` (SDK may auto-append JSON text for
170
+ * non-object roots).
171
+ *
172
+ * @typeParam T - Array payload type.
173
+ * @param data - Array to return as `structuredContent`.
174
+ * @returns Tool result with JSON text and the array as `structuredContent`.
175
+ */
176
+ export declare function array<T extends unknown[]>(data: T): CallToolResult;
177
+ /**
178
+ * Runtime data for a view-bound tool result (legacy widget helper).
179
+ *
180
+ * @deprecated Prefer returning a plain {@link CallToolResult} from a tool
181
+ * registered with `view: { name }`. Put view props in `structuredContent` and
182
+ * model-facing text in `content`.
183
+ *
184
+ * @typeParam TProps - Props object placed in `structuredContent`.
185
+ */
186
+ export interface WidgetResponseConfig<TProps extends Record<string, unknown> = Record<string, unknown>> {
187
+ /** View-facing data sent as `structuredContent`. */
188
+ props?: TProps;
189
+ /**
190
+ * Legacy alias for {@link WidgetResponseConfig.props}.
191
+ *
192
+ * @deprecated Use `props` instead.
193
+ */
194
+ data?: TProps;
195
+ /** Model-facing helper/`CallToolResult` whose `content` is forwarded. */
196
+ output?: CallToolResult | TypedCallToolResult;
197
+ /** Extra result `_meta` for the view. */
198
+ metadata?: Record<string, unknown>;
199
+ /** Override text when `output` is omitted or should be replaced. */
200
+ message?: string;
201
+ }
202
+ /**
203
+ * Create a view/widget tool result (`props` → `structuredContent`).
204
+ *
205
+ * @deprecated Prefer a plain {@link CallToolResult} with `view:` on the tool
206
+ * definition:
207
+ * `{ content: [{ type: "text", text }], structuredContent: props }`.
208
+ *
209
+ * @typeParam TProps - Props object type.
210
+ * @param config - Runtime view data.
211
+ * @returns Tool result with props in `structuredContent`.
212
+ */
213
+ export declare function widget<TProps extends Record<string, unknown> = Record<string, unknown>>(config: WidgetResponseConfig<TProps>): TypedCallToolResult<TProps>;
214
+ /**
215
+ * Merge several tool results into one (`content` concatenated; objects shallow-merged).
216
+ *
217
+ * @deprecated Prefer building a single raw {@link CallToolResult} with the
218
+ * desired `content` array.
219
+ *
220
+ * @param results - Results to merge.
221
+ * @returns Combined tool result.
222
+ */
223
+ export declare function mix(...results: CallToolResult[]): CallToolResult;