fastmcp
FastMCP TypeScript framework patterns for MCP servers. Auto-loads when building MCP servers, creating tools/resources/prompts, implementing authentication, configuring transports, or working with FastMCP in TypeScript.
What this skill does
# FastMCP Development Skill
FastMCP is a TypeScript framework for building Model Context Protocol (MCP) servers. This skill provides patterns for tools, resources, prompts, authentication, and transport configuration.
## Installation
```bash
npm install fastmcp
```
## Basic Server Setup
```typescript
import { FastMCP } from "fastmcp";
import { z } from "zod";
const server = new FastMCP({
name: "My Server",
version: "1.0.0",
});
server.start({ transportType: "stdio" });
```
## Tools
### Basic Tool with Zod Schema
```typescript
server.addTool({
name: "add",
description: "Add two numbers",
parameters: z.object({
a: z.number(),
b: z.number(),
}),
execute: async (args) => {
return String(args.a + args.b);
},
});
```
### Tool Without Parameters
```typescript
server.addTool({
name: "sayHello",
description: "Say hello",
execute: async () => {
return "Hello, world!";
},
});
```
### Tool with Logging
```typescript
server.addTool({
name: "download",
parameters: z.object({ url: z.string() }),
execute: async (args, { log }) => {
log.info("Downloading file...", { url: args.url });
// ... process ...
log.info("Downloaded file");
return "done";
},
});
```
### Tool with Progress Reporting
```typescript
server.addTool({
name: "download",
execute: async (args, { reportProgress }) => {
await reportProgress({ progress: 0, total: 100 });
// ... process ...
await reportProgress({ progress: 100, total: 100 });
return "done";
},
});
```
### Tool with Streaming Output
```typescript
server.addTool({
name: "generateText",
parameters: z.object({ prompt: z.string() }),
annotations: {
streamingHint: true,
readOnlyHint: true,
},
execute: async (args, { streamContent }) => {
await streamContent({ type: "text", text: "Starting...\n" });
const words = "The quick brown fox".split(" ");
for (const word of words) {
await streamContent({ type: "text", text: word + " " });
await new Promise(resolve => setTimeout(resolve, 300));
}
return;
},
});
```
### Tool with Multiple Content Types
```typescript
server.addTool({
name: "download",
description: "Download a file",
parameters: z.object({ url: z.string() }),
execute: async (args) => {
return {
content: [
{ type: "text", text: "First message" },
{ type: "text", text: "Second message" },
],
};
},
});
```
### Tool with Image Content
```typescript
import { imageContent } from "fastmcp";
server.addTool({
name: "getImage",
execute: async (args) => {
return imageContent({
url: "https://example.com/image.png",
});
// Or: path: "/path/to/image.png"
// Or: buffer: Buffer.from(...)
},
});
```
### Tool with Audio Content
```typescript
import { audioContent } from "fastmcp";
server.addTool({
name: "getAudio",
execute: async (args) => {
return audioContent({
url: "https://example.com/audio.mp3",
});
},
});
```
### Tool with Error Handling
```typescript
import { UserError } from "fastmcp";
server.addTool({
name: "download",
execute: async (args) => {
if (args.url.startsWith("https://example.com")) {
throw new UserError("This URL is not allowed");
}
return "done";
},
});
```
### Tool with Annotations
```typescript
server.addTool({
name: "fetch-content",
description: "Fetch content from a URL",
parameters: z.object({ url: z.string() }),
annotations: {
title: "Web Content Fetcher",
readOnlyHint: true,
openWorldHint: true,
},
execute: async (args) => {
return await fetchWebpageContent(args.url);
},
});
```
### Tool with Authorization
```typescript
server.addTool({
name: "admin-tool",
description: "An admin-only tool",
canAccess: (auth) => auth?.role === "admin",
execute: async () => "Welcome, admin!",
});
```
## Alternative Schema Libraries
### ArkType
```typescript
import { type } from "arktype";
server.addTool({
name: "fetch-arktype",
parameters: type({ url: "string" }),
execute: async (args) => {
return await fetchWebpageContent(args.url);
},
});
```
### Valibot
```typescript
import * as v from "valibot";
server.addTool({
name: "fetch-valibot",
parameters: v.object({ url: v.string() }),
execute: async (args) => {
return await fetchWebpageContent(args.url);
},
});
```
## Resources
### Basic Resource
```typescript
server.addResource({
uri: "file:///logs/app.log",
name: "Application Logs",
mimeType: "text/plain",
async load() {
return {
text: await readLogFile(),
};
},
});
```
### Resource with Binary Content
```typescript
server.addResource({
uri: "file:///logs/app.log",
async load() {
return {
blob: 'base64-encoded-data'
};
},
});
```
### Resource Template
```typescript
server.addResourceTemplate({
uriTemplate: "file:///logs/{name}.log",
name: "Application Logs",
mimeType: "text/plain",
arguments: [
{
name: "name",
description: "Name of the log",
required: true,
},
],
async load({ name }) {
return {
text: `Log content for ${name}`,
};
},
});
```
### Resource Template with Auto-Completion
```typescript
server.addResourceTemplate({
uriTemplate: "file:///logs/{name}.log",
arguments: [
{
name: "name",
description: "Name of the log",
required: true,
complete: async (value) => {
if (value === "Example") {
return { values: ["Example Log"] };
}
return { values: [] };
},
},
],
async load({ name }) {
return {
text: `Log content for ${name}`,
};
},
});
```
### Embedded Resources in Tools
```typescript
server.addTool({
name: "get_user_data",
parameters: z.object({ userId: z.string() }),
execute: async (args) => {
return {
content: [
{
type: "resource",
resource: await server.embedded(`user://profile/${args.userId}`),
},
],
};
},
});
```
## Prompts
### Basic Prompt
```typescript
server.addPrompt({
name: "git-commit",
description: "Generate a Git commit message",
arguments: [
{
name: "changes",
description: "Git diff or description of changes",
required: true,
},
],
load: async (args) => {
return "Generate a concise commit message:\n\n" + args.changes;
},
});
```
### Prompt with Auto-Completion
```typescript
server.addPrompt({
name: "countryPoem",
description: "Writes a poem about a country",
load: async ({ name }) => {
return "Write a poem about " + name + "!";
},
arguments: [
{
name: "name",
description: "Name of the country",
required: true,
complete: async (value) => {
if (value === "Germ") {
return { values: ["Germany"] };
}
return { values: [] };
},
},
],
});
```
### Prompt with Enum Arguments
```typescript
server.addPrompt({
name: "countryPoem",
description: "Writes a poem about a country",
load: async ({ name }) => {
return "Write a poem about " + name + "!";
},
arguments: [
{
name: "name",
description: "Name of the country",
required: true,
enum: ["Germany", "France", "Italy"],
},
],
});
```
## Authentication
### Basic API Key Authentication
```typescript
const server = new FastMCP({
name: "My Server",
version: "1.0.0",
authenticate: (request) => {
const apiKey = request.headers["x-api-key"];
if (apiKey !== "expected-key") {
throw new Response(null, {
status: 401,
statusText: "Unauthorized",
});
}
return { id: 1 };
},
});
server.addTool({
name: "sayHello",
execute: async (args, { session }) => {
return "Hello, " + session.id + "!";
},
});
```
### Role-Based Authentication
```typescript
const server = new FastMCP<{ role: "admin" | "user" }>({
authenticate: async (request) => {
const role = Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.