-
Notifications
You must be signed in to change notification settings - Fork 92
feat(xmcp): add ergonomic sampling helper for tool handlers #542
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FiammaMuscari
wants to merge
3
commits into
basementstudio:canary
Choose a base branch
from
FiammaMuscari:feat/sampling-helper
base: canary
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
FiammaMuscari marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| # HTTP Transport Example | ||
|
|
||
| This example demonstrates `extra.sample()` over Streamable HTTP. | ||
|
|
||
| ## Sampling behavior in HTTP examples | ||
|
|
||
| - With MCP-compatible clients, `extra.sample()` runs the real | ||
| `sampling/createMessage` flow and completes the full sampling loop. | ||
| - With MCPJam, `sampling/createMessage` is not supported today and returns | ||
| `-32601 Method not found`, so the demo tools fall back to deterministic local | ||
| responses instead of failing. | ||
|
|
||
| Use a compatible HTTP MCP client as the proof that real sampling succeeds over | ||
| HTTP. | ||
| Use MCPJam only to verify the fallback path and graceful degradation. | ||
|
|
||
| ## Run the server | ||
|
|
||
| From this directory: | ||
|
|
||
| ```bash | ||
| pnpm install | ||
| pnpm dev | ||
| ``` | ||
|
|
||
| Use the MCP URL printed in the terminal when the server starts. | ||
| If the default port is free, that URL will usually be `http://localhost:3000/mcp`. | ||
|
|
||
| ## Open it in MCPJam | ||
|
|
||
| Connect MCPJam to the HTTP server URL printed by `pnpm dev`. | ||
|
|
||
| ```txt | ||
| http://localhost:3000/mcp | ||
| ``` | ||
|
|
||
| ## Try the sampling tools | ||
|
|
||
| Once MCPJam opens: | ||
|
|
||
| 1. Confirm the server is connected in the `MCP Servers` tab. | ||
| 2. Open the `Tools` tab and run `summarize_with_sample` with: | ||
|
|
||
| ```json | ||
| { | ||
| "topic": "Model Context Protocol" | ||
| } | ||
| ``` | ||
|
|
||
| With an MCP-compatible client, this exercises the basic `extra.sample()` flow | ||
| and returns sampled text. | ||
| With MCPJam, it returns a deterministic fallback message instead of failing the | ||
| tool run. | ||
|
|
||
| 3. Run `research_topic` with: | ||
|
|
||
| ```json | ||
| { | ||
| "topic": "xmcp sampling helper" | ||
| } | ||
| ``` | ||
|
|
||
| With an MCP-compatible client, this exercises the local tool loop. The model | ||
| asks for `search_docs`, xmcp runs that tool, and then the sampling helper | ||
| continues the `tool_use -> tool_result -> continue` flow before returning the | ||
| final text. | ||
| With MCPJam, it falls back to calling `search_docs` directly so the example | ||
| still completes end-to-end over HTTP. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { z } from "zod"; | ||
| import { | ||
| getSampleTextContent, | ||
| type InferSchema, | ||
| type ToolExtraArguments, | ||
| } from "xmcp"; | ||
| import searchDocs from "./search-docs"; | ||
|
|
||
| export const schema = { | ||
| topic: z.string().describe("Topic to research"), | ||
| }; | ||
|
|
||
| export const metadata = { | ||
| name: "research_topic", | ||
| description: "Demonstrates extra.sample() with local tool execution", | ||
| }; | ||
|
|
||
| export default async function researchTopic( | ||
| { topic }: InferSchema<typeof schema>, | ||
| extra: ToolExtraArguments | ||
| ) { | ||
| try { | ||
| const result = await extra.sample({ | ||
| messages: [ | ||
| { | ||
| role: "user", | ||
| content: { | ||
| type: "text", | ||
| text: `Research ${topic} using the local tools and give me a short answer.`, | ||
| }, | ||
| }, | ||
| ], | ||
|
FiammaMuscari marked this conversation as resolved.
Outdated
|
||
| tools: ["search_docs"], | ||
| toolChoice: { mode: "required" }, | ||
| maxTokens: 500, | ||
| maxSteps: 4, | ||
| }); | ||
|
|
||
| return getSampleTextContent(result) || "No text returned."; | ||
| } catch (error) { | ||
| const message = | ||
| error instanceof Error && error.message ? error.message : String(error); | ||
|
|
||
| if ( | ||
| !message.includes("does not support MCP sampling") && | ||
| !message.includes("sampling/createMessage") && | ||
| !message.includes("Method not found") | ||
| ) { | ||
| throw error; | ||
| } | ||
|
FiammaMuscari marked this conversation as resolved.
Outdated
|
||
|
|
||
| const docsHit = await searchDocs({ query: topic }); | ||
|
|
||
| return `Fallback research for "${topic}": the connected MCP client does not implement sampling/createMessage yet, so this demo called the local search_docs tool directly. ${docsHit}`; | ||
|
FiammaMuscari marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { z } from "zod"; | ||
| import { type InferSchema } from "xmcp"; | ||
|
|
||
| export const schema = { | ||
| query: z.string().describe("Query to look up in the canned docs"), | ||
| }; | ||
|
|
||
| export const metadata = { | ||
| name: "search_docs", | ||
| description: "Returns canned xmcp notes for the sampling helper demo", | ||
| }; | ||
|
|
||
| export default async function searchDocs({ | ||
| query, | ||
| }: InferSchema<typeof schema>) { | ||
| return `Top hit for "${query}": extra.sample() lets xmcp tool handlers request client-side MCP sampling, optionally expose local tools, and continue the tool_use -> tool_result loop until the model finishes.`; | ||
| } |
54 changes: 54 additions & 0 deletions
54
examples/http-transport/src/tools/summarize-with-sample.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import { z } from "zod"; | ||
| import { | ||
| getSampleContext, | ||
| type InferSchema, | ||
| type ToolExtraArguments, | ||
| } from "xmcp"; | ||
|
|
||
| export const schema = { | ||
| topic: z.string().describe("Topic to summarize"), | ||
| }; | ||
|
|
||
| export const outputSchema = { | ||
| summary: z.string(), | ||
| }; | ||
|
|
||
| export const metadata = { | ||
| name: "summarize_with_sample", | ||
| description: "Demonstrates extra.sample() without tool use", | ||
| }; | ||
|
|
||
| export default async function summarizeWithSample( | ||
| { topic }: InferSchema<typeof schema>, | ||
| extra: ToolExtraArguments | ||
| ) { | ||
| try { | ||
| const result = await extra.sample({ | ||
| messages: [ | ||
| { | ||
| role: "user", | ||
| content: { | ||
| type: "text", | ||
| text: `Write a concise summary about ${topic}.`, | ||
| }, | ||
| }, | ||
| ], | ||
| maxTokens: 300, | ||
| }); | ||
|
|
||
| return getSampleContext(result) || "The client did not return text content."; | ||
| } catch (error) { | ||
| const message = | ||
| error instanceof Error && error.message ? error.message : String(error); | ||
|
|
||
| if ( | ||
| !message.includes("does not support MCP sampling") && | ||
| !message.includes("sampling/createMessage") && | ||
| !message.includes("Method not found") | ||
| ) { | ||
| throw error; | ||
| } | ||
|
|
||
| return `Fallback summary for "${topic}": the connected MCP client does not implement sampling/createMessage yet, so this demo returned a deterministic response instead of model-generated text.`; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.