implementing-mcp-tools
Skill33 starsChanged 8 months agoMITView on GitHub
Implement new MCP tools in the deno-mcp-template project. Provides the exact file structure, type signatures, registration steps, and patterns for standard tools, sampling tools, form and URL elicitation, resource-backed tools, and notification tools. Use when adding a new tool, creating MCP tools, or asking how tools work in this project.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- PostHog/posthogtheir own version, first seen Oct 4, 2026
- PostHog/posthog-fosstheir own version, first seen Oct 4, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- PostHog/posthog★ 40ksame name
- PostHog/posthog-foss★ 721same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository3 other files it gives its agents.
- .cursor/rules/project.mdcCursor rule
- implementing-mcp-promptsSkill
- implementing-mcp-resourcesSkill
The file
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 2 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 21
Every tool follows this structure.
- Very specific: line 80
Import the tool: import myTool from "./myTool.ts".
- Very specific: line 81
Add it to the tools array:
- Very specific: line 109
Always validate with Zod safeParse.
- Very specific: line 142
Use _mcp (unused) in the callback factory.
- Very specific: line 146
Use mcp.server.createMessage() to request LLM completions:
- Very specific: line 184
Use mcp.server.elicitInput() with a JSON Schema (requestedSchema):
- Distinctive: line 220
Do not log secrets submitted on elicitation HTML forms.
- Distinctive: line 224
Import resource helpers and mutate state.
- Very specific: line 248
Use mcp.sendToolListChanged(), mcp.sendPromptListChanged(), or mcp.sendResourceListChanged() to notify clients that available items have …
- Very specific: line 252
Add annotations to config for client hints:
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Implementing MCP Tools
Workflow
Task Progress:
- [ ] Step 1: Create tool file in src/mcp/tools/
- [ ] Step 2: Define Zod schema, name, config, and callback
- [ ] Step 3: Export as default ToolModule
- [ ] Step 4: Register in src/mcp/tools/mod.ts
- [ ] Step 5: Run `deno task ci` to verifyTool File Template
Every tool follows this structure. Create a new file in src/mcp/tools/.
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod/v3";
import type { ToolConfig, ToolModule } from "$/shared/types.ts";
import {
createCallToolErrorResponse,
createCallToolTextResponse,
} from "$/shared/utils.ts";
// 1. Input schema
const schema = z.object({
myField: z.string().min(1, "Required").describe("What this field does"),
});
// 2. Tool name (kebab-case)
const name = "my-tool-name";
// 3. Config
// deno-lint-ignore no-explicit-any
const config: ToolConfig<typeof schema.shape, any> = {
title: "Human-readable title",
description: "What this tool does — shown to the LLM",
inputSchema: schema.shape,
};
// 4. Callback factory: receives McpServer, returns the handler
// deno-lint-ignore no-explicit-any
const callback = (_mcp: McpServer) => async (args: any): Promise<CallToolResult> => {
const parsed = schema.safeParse(args);
if (!parsed.success) {
return createCallToolErrorResponse({
error: "Invalid arguments",
details: parsed.error.flatten(),
received: args,
});
}
const { myField } = parsed.data;
// ... tool logic ...
return createCallToolTextResponse({ result: myField });
};
// 5. Export as ToolModule tuple
// deno-lint-ignore no-explicit-any
const module: ToolModule<typeof schema.shape, any> = [name, config, callback];
export default module;Registration
In src/mcp/tools/mod.ts:
- Import the tool:
import myTool from "./myTool.ts"; - Add it to the
toolsarray:
export const tools: ToolModule<any>[] = [
// ... existing tools
myTool,
];The ToolManager in the same file handles binding and registration automatically.
Key Types
From src/shared/types.ts:
ToolModule<InputArgs, OutputArgs>— Export format:[name, config, callbackFactory]ToolConfig<InputArgs, OutputArgs>—{ title, description, inputSchema, outputSchema?, annotations? }ToolPlugin— Bound format:[name, config, callback](created byToolManager)
Response Helpers
From src/shared/utils.ts:
createCallToolTextResponse(obj, structuredContent?)— Wrapsobjas JSON text contentcreateCallToolErrorResponse(obj, structuredContent?)— Same but setsisError: true
Validation Pattern
Always validate with Zod safeParse. For optional args, use args ?? {}:
const parsed = schema.safeParse(args ?? {});
if (!parsed.success) {
return createCallToolErrorResponse({
error: "Invalid arguments",
details: parsed.error.flatten(),
received: args,
});
}Error Handling Pattern
Wrap operational logic in try/catch:
try {
const result = await doSomething(parsed.data);
return createCallToolTextResponse({ result });
} catch (error) {
return createCallToolErrorResponse({
error: error instanceof Error ? error.message : "Unknown error",
operation: "my-operation",
});
}Tool Categories
Standard Tool (no MCP server interaction)
Use _mcp (unused) in the callback factory. See the template above.
Sampling Tool (LLM-powered)
Use mcp.server.createMessage() to request LLM completions:
const callback = (mcp: McpServer) => async (args: any): Promise<CallToolResult> => {
// ... validate args ...
const response = await mcp.server.createMessage(
{
messages: [{ role: "user", content: { type: "text", text: prompt } }],
maxTokens: 1024,
temperature: 0.7,
},
{ timeout: 30000 },
);
const content = Array.isArray(response.content)
? response.content[0]
: response.content;
if (!content || content.type !== "text") {
return createCallToolErrorResponse({ error: "No text response from sampling" });
}
return createCallToolTextResponse({ result: content.text });
};Elicitation Tool (user input)
Experimental elicitation is enabled in src/mcp/serverDefinition.ts (experimentalElicitation: true). Two modes matter in practice:
| Mode | Use case | Mechanism |
form | Structured, non-sensitive fields; validated in the MCP client UI | await mcp.server.elicitInput({ mode: "form", message, requestedSchema }) |
url | Sensitive or browser-only flows (confirmations, OAuth, secrets typed in your page) | Throw UrlElicitationRequiredError with a URL; complete out-of-band, then createElicitationCompletionNotifier fires notifications/elicitation/complete |
Form mode
Use mcp.server.elicitInput() with a JSON Schema (requestedSchema):
const callback = (mcp: McpServer) => async (args: any): Promise<CallToolResult> => {
// ... validate args ...
const result = await mcp.server.elicitInput({
mode: "form",
message: "Please provide details",
requestedSchema: {
type: "object",
properties: {
name: { type: "string", title: "Name", description: "Your name" },
},
required: ["name"],
},
});
return createCallToolTextResponse({ elicitationResult: result });
};Branch on result.action (accept with content, decline, or cancelled) before assuming data exists. For multiple steps, call elicitInput more than once in one tool (see src/mcp/tools/elicitFormWizard.ts).
URL mode
The client opens a browser URL you control. The tool does not return a normal success result; it throws UrlElicitationRequiredError from @modelcontextprotocol/sdk/types.js with an array of { mode: "url", message, url, elicitationId }.
In this template:
McpServerFactoryContextincludesurlElicitation: { baseUrl, registry }(src/mcp/context.ts). ResolvebaseUrlwithMCP_PUBLIC_BASE_URLor the derived bind URL (src/shared/publicBaseUrl.ts).- Register pending state and the SDK notifier:
mcp.server.createElicitationCompletionNotifier(elicitationId), thenctx.urlElicitation.registry.registerPending({ elicitationId, sessionId, label, completionNotifier }). - Require
extra.sessionIdon the tool handler (streamable HTTP). STDIO has no session; returncreateCallToolErrorResponseinstead of throwing. - Browser routes live in
src/app/http/urlElicitationRoutes.ts(GET/POST/mcp-elicitation/confirm). They validate session + elicitation id against the registry and active transport, then callregistry.complete(elicitationId). Bearer auth is skipped for/mcp-elicitationso users are not prompted for the MCP token in a normal browser tab (src/app/http/httpBearerAuthMiddleware.ts). - Reference implementation:
registerUrlElicitationDemoToolinsrc/mcp/tools/urlElicitationDemo.ts, wired fromsrc/mcp/mod.tswhenmcpServerDefinition.urlElicitationDemois true.
Do not log secrets submitted on elicitation HTML forms.
Resource-Backed Tool
Import resource helpers and mutate state. Resource subscriptions handle notifications automatically via KV watchers:
import { COUNTER_URI, incrementCounterValue } from "../resources/counter.ts";
// In callback:
const value = await incrementCounterValue(delta);
return createCallToolTextResponse({ value, uri: COUNTER_URI });Notification Tool (logging)
Use mcp.server.sendLoggingMessage():
await mcp.server.sendLoggingMessage({
level: "info", // debug | info | notice | warning | error | critical | alert | emergency
logger: "my-logger",
data: { message: "Something happened" },
});Notification Tool (list changed)
Use mcp.sendToolListChanged(), mcp.sendPromptListChanged(), or mcp.sendResourceListChanged() to notify clients that available items have changed.
Annotations
Add annotations to config for client hints:
const config: ToolConfig<typeof schema.shape, any> = {
title: "My Tool",
description: "...",
inputSchema: schema.shape,
annotations: {
title: "My Tool",
readOnlyHint: true,
openWorldHint: false,
},
};Additional Resources
- For complete tool examples by category, see examples.md
- MCP Tool spec: https://modelcontextprotocol.io/specification/2025-06-18/server/tools
- MCP Sampling: https://modelcontextprotocol.io/docs/concepts/sampling
- MCP Elicitation: https://modelcontextprotocol.io/docs/concepts/elicitation
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

