Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

fastmcp

БесплатноБез исполняемых скриптовНе проверен

FastMCP is a Python framework for building Model Context Protocol (MCP) servers and clients: a decorated Python function becomes a tool, resource or prompt…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

FastMCP — Build MCP servers and clients in Python

Overview

FastMCP wraps ordinary Python functions as MCP tools, resources and prompts. Names, descriptions and input schemas come from the function signature, type hints and docstring; validation, transports and protocol negotiation are handled by the framework. The same package contains a client for calling any MCP server and a fastmcp CLI for running, inspecting, calling and installing servers. This skill targets FastMCP 4.x, imported as from fastmcp import FastMCP.

Instructions

Installation

uv add fastmcp          # inside a uv project (recommended)
pip install fastmcp     # any virtual environment
fastmcp version         # prints FastMCP, MCP and Python versions

Define a server

# stock_server.py
from typing import Annotated

from pydantic import Field
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError

mcp = FastMCP(
    "Warehouse Stock",
    instructions="Look up and reserve bike parts. Call find_items before reserve_item.",
)

STOCK = {
    "BRK-2210": {"name": "Disc brake pads", "on_hand": 48, "bin": "A-14"},
    "CHN-1180": {"name": "11-speed chain", "on_hand": 6, "bin": "C-03"},
    "TIR-0700": {"name": "700x28c road tire", "on_hand": 0, "bin": "D-21"},
}

@mcp.tool
def find_items(query: str, max_results: int = 10) -> list[dict]:
    """Search stock by part name or SKU.

    Args:
        query: Part name fragment or SKU, for example "chain" or "BRK-2210".
        max_results: Maximum number of rows to return.
    """
    q = query.lower()
    rows = [{"sku": sku, **item} for sku, item in STOCK.items()
            if q in sku.lower() or q in item["name"].lower()]
    return rows[:max_results]

@mcp.tool(annotations={"readOnlyHint": False, "idempotentHint": False})
def reserve_item(sku: str, quantity: Annotated[int, Field(ge=1, le=100)]) -> dict:
    """Reserve units of one SKU for an order and return the remaining stock."""
    item = STOCK.get(sku)
    if item is None:
        raise ToolError(f"Unknown SKU {sku}. Call find_items first.")
    if item["on_hand"] < quantity:
        raise ToolError(f"Only {item['on_hand']} of {sku} on hand.")
    item["on_hand"] -= quantity
    return {"sku": sku, "reserved": quantity, "on_hand": item["on_hand"]}

@mcp.resource("stock://bins/{bin_id}")
def bin_contents(bin_id: str) -> dict:
    """Everything stored in one warehouse bin."""
    return {sku: item for sku, item in STOCK.items() if item["bin"] == bin_id}

@mcp.prompt
def restock_report(threshold: int = 10) -> str:
    """Ask for a restock list for parts below a threshold."""
    return f"List every part with fewer than {threshold} units on hand and suggest order quantities."

if __name__ == "__main__":
    mcp.run()
  • Parameters without a default are required. Annotated[..., Field(...)] adds constraints and descriptions; docstring Args: entries become parameter descriptions. A resource URI with {placeholders} is a template; without them it is a fixed resource.
  • ToolError messages always reach the client. Other exceptions are also reported unless the server is created with mask_error_details=True.
  • For logging and progress inside a tool, make it async and add a parameter ctx: Context = CurrentContext() (from fastmcp.dependencies import CurrentContext, from fastmcp.server.context import Context), then await ctx.info("...") or await ctx.report_progress(progress=50, total=100).

Run it

python stock_server.py                                          # stdio, the default transport
fastmcp run stock_server.py:mcp --transport http --port 8000    # serves http://localhost:8000/mcp
fastmcp run stock_server.py --reload                            # restart on file changes
fastmcp dev inspector stock_server.py                           # open the MCP Inspector in a browser

fastmcp run imports the server object (it looks for mcp, server or app) and ignores the if __name__ == "__main__": block. In code, HTTP is mcp.run(transport="http", host="127.0.0.1", port=8000). To serve through an ASGI server, expose app = mcp.http_app() in a module and start it with Uvicorn.

Inspect and call from the terminal

fastmcp inspect stock_server.py
fastmcp list stock_server.py --resources --prompts
fastmcp call stock_server.py find_items query=chain
fastmcp call stock_server.py stock://bins/A-14
fastmcp call stock_server.py restock_report --prompt threshold=5
fastmcp call http://localhost:8000/mcp reserve_item sku=CHN-1180 quantity=2 --auth none

Add --json to list or call for machine-readable output. Arguments are key=value pairs coerced to the schema types; pass one JSON object for nested input. For URL targets the CLI tries OAuth by default: use --auth none for local servers, or pass a bearer token value to --auth.

Install into an agent

fastmcp install claude-code stock_server.py --name warehouse-stock
fastmcp instal
Полный SKILL.md на GitHub

Установить fastmcp в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл fastmcp?

FastMCP is a Python framework for building Model Context Protocol (MCP) servers and clients: a decorated Python function becomes a tool, resource or prompt that an AI agent can call, with the schema generated from type hints. Use when someone asks to "build an MCP server in Python", "create a FastMCP server", "expose this function to Claude as a tool", "turn our OpenAPI spec into MCP tools", "test my MCP server", "call an MCP server from Python", or "install my server into Claude Code or Cursor". Covers tools, resources and prompts, stdio and HTTP transports, the fastmcp CLI, in-memory tests, token authentication, and generation from OpenAPI.

Как установить скилл fastmcp?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл fastmcp запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить fastmcp с