code_style

A Python style guide for building MCP servers with FastMCP, the higher-level interface of the official Python MCP software development kit.

In plain words
What is it for?
Use it when writing or reviewing FastMCP servers, especially their tool functions, resource handlers, type hints, and lifecycle code.
Why use it?
It sets consistent rules for defining tools, inputs, documentation, resources, logging, progress, and server startup.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/asheng008/unifiles-mcp/code_style
Clone the repo
git clone --depth 1 https://github.com/Asheng008/unifiles-mcp

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 1,530 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.01530
Opus 5 $0.00000 $0.00765
Sonnet 5 $0.00000 $0.00306
Haiku 4.5 $0.00000 $0.00153

Measured 2d ago against content hash 3bc4daa3370b, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

code_style scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/code_style.mdc · 141 lines

How it starts

The opening of the file, as written. The whole thing — 141 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python MCP SDK (FastMCP) Code Style

Context: 适用于使用 mcp 官方 SDK 的 FastMCP 高级接口开发服务器。 Focus: 使用装饰器、类型提示自动生成 Schema、简化生命周期管理。 Reference: https://pypi.org/project/mcp/

1. 核心原则 (Core Principles)

  • FastMCP 优先: 始终使用 mcp.server.fastmcp.FastMCP 类,避免直接操作底层的 Server 类。
  • 类型驱动: 利用 Python 类型提示 (str, int, bool, list, 等) 自动生成 MCP Schema;优先使用简单类型平铺传参,避免用单个字典/对象包住所有参数。
  • 文档即描述: 函数的 Docstring 会自动转换为工具/资源的描述字段。
  • 上下文感知: 使用 Context 对象处理日志、进度报告和二进制数据。

2. 基础架构 (Basic Structure)

标准的 FastMCP 服务器结构如下:

from mcp.server.fastmcp import FastMCP, Context, Image

# 1. 初始化服务器
mcp = FastMCP("My Server")

# 2. 定义工具 (Tools)
@mcp.tool()
async def calculate_metrics(data: list[float], threshold: float = 0.5) -> dict[str, float]:
    """
    计算数据指标。
    
    Args:
        data: 输入的数据列表
        threshold: 过滤阈值
    """
    filtered = [x for x in data if x > threshold]
    return {
        "count": len(filtered),
        "average": sum(filtered) / len(filtered) if filtered else 0
    }

# 3. 定义资源 (Resources)
@mcp.resource("file://{path}")
def read_custom_file(path: str) -> str:
    """读取自定义格式文件"""
    return f"Mock content for {path}"

# 4. 运行入口
if __name__ == "__main__":
    mcp.run()

3. 关键模式 (Key Patterns)

3.1 工具传参:简单类型平铺 (Simple Flat Parameters)

优先使用简单类型平铺传参,不要用单个 Pydantic 模型或字典包住所有参数。这样 MCP 客户端只需传 key: value,无需构造 params: { ... } 对象。校验在函数内部完成。

  • 必填/常用参数:strintboollisttuple 等,用 Annotated[T, Field(description="...")] 写描述。
  • 可选参数:带默认值即可,如 limit: int = 10
  • 仅在确有复杂嵌套、且多工具复用时,再考虑 Pydantic 模型。
from typing import Annotated
from pydantic import Field

@mcp.tool()
async def search_database(
    query: Annotated[str, Field(description="搜索关键词")],
    limit: Annotated[int, Field(description="最多返回条数")] = 10,
    tags: list[str] | None = None,
    ctx: Context,
) -> list[str]:
    """在数据库中搜索内容。"""
    if tags is None:
        tags = []
    # 校验在内部完成,如 limit 范围等
    return [f"Result for {query}"]

Read the full file on GitHub · 141 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 141 lines · 1,530 tokens per session scan A 3bc4daa3370b

Subscribe to this mod's changes

code_style is a cursor rule published in the GitHub repository Asheng008/unifiles-mcp (0 stars, last pushed 5mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 1,530 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.