Dynamic Per-User Tool Generation MCP Server

Dynamic Per-User Tool Generation MCP Server

Enables dynamic generation of tools based on user-specific permissions from an external API. Users receive personalized tools tailored to their access rights, with intelligent caching and graceful fallback to static tools.

Category
访问服务器

README

MCP Server with Dynamic Per-User Tool Generation

A Model Context Protocol (MCP) server implementation using FastMCP that dynamically generates tools based on user permissions from an external API.

Features

  • Dynamic Tool Generation: Tools are generated at runtime based on user-specific schemas from an external API
  • Per-User Permissions: Each authenticated user receives tools tailored to their permissions
  • Intelligent Caching: Both API schemas and generated tools are cached with TTL for performance
  • Graceful Degradation: Falls back to static tools if API is unavailable
  • Comprehensive Logging: Detailed logging at INFO, DEBUG, WARNING, and ERROR levels
  • Thread-Safe: Concurrent requests from multiple users are handled safely

Architecture

Components

  1. mcp_server.py - Main server entry point

    • Initializes FastMCP server
    • Registers static tools (add, echo, multiply)
    • Sets up dynamic tool middleware
  2. api_client.py - External API integration

    • FormSchemaClient: Fetches and parses schemas from external API
    • FormSchemaCache: Caches API responses with TTL
    • Converts API field definitions to JSON Schema format
  3. dynamic_tool_manager.py - Tool lifecycle management

    • DynamicToolManager: Manages per-user tool storage
    • Thread-safe caching with TTL
    • Cache statistics and invalidation
  4. tool_function_factory.py - Dynamic function generation

    • Creates typed async functions from JSON schemas
    • Generates proper inspect.Signature for FastMCP validation
    • Maps JSON Schema types to Python types
  5. tool_execution_handler.py - Tool execution backend

    • ToolExecutionRouter: Routes tool calls to appropriate handlers
    • Specialized handlers for different tool types
    • Structured error responses
  6. dynamic_tool_middleware.py - FastMCP middleware

    • Intercepts list/tools requests
    • Extracts authentication tokens
    • Generates and caches user-specific tools
    • Returns combined static + dynamic tools

Installation

  1. Install dependencies:

    pip install -r requirements.txt
    
  2. Configure the API URL: Edit mcp_server.py and set the FORM_SCHEMA_API_URL to your external API endpoint:

    FORM_SCHEMA_API_URL = "http://172.16.11.131/api/module/request/form"
    

Usage

Starting the Server

python mcp_server.py

The server will start on http://127.0.0.1:9092/mcp

Authentication

The server expects authentication via HTTP Authorization header:

Authorization: Bearer <your-token>

The token is used to:

  1. Fetch user-specific schema from the external API
  2. Generate tools with fields the user has permission to access
  3. Cache tools for subsequent requests

Available Tools

Static Tools (Always Available)

  • add(a: int, b: int) -> int - Adds two numbers
  • echo(message: str) -> str - Echoes a message
  • multiply(a: int, b: int) -> int - Multiplies two numbers

Dynamic Tools (User-Specific)

  • create_request(...) - Creates a request with fields based on user permissions
    • Parameters are dynamically generated from the external API schema
    • Each user sees different parameters based on their permissions
    • Required fields, enums, and types are enforced

How It Works

Request Flow

  1. Client sends list/tools request with Authorization: Bearer <token>

  2. Middleware intercepts the request:

    • Extracts auth token from header
    • Checks if tools are cached for this user
    • If cached: Returns cached tools
    • If not cached: Proceeds to generation
  3. Tool Generation:

    • Fetches schema from external API with user's token
    • Parses API response into JSON Schema
    • Creates typed async function with proper signature
    • Converts function to FastMCP Tool object
    • Caches the tool for future requests
  4. Response:

    • Returns list of static tools + dynamic tools
    • Client sees tools specific to their permissions

Tool Execution Flow

  1. Client calls create_request tool with arguments

  2. FastMCP validates arguments against the generated function signature

  3. Tool execution handler:

    • Receives validated arguments
    • Processes the request
    • Returns structured response with ID, timestamp, status

Configuration

Cache TTL

Both schema cache and tool cache use 5-minute TTL by default. To change:

# In mcp_server.py
schema_client = FormSchemaClient(
    api_url=FORM_SCHEMA_API_URL,
    cache_ttl=300,  # Change this value (seconds)
    verbose=True
)
tool_manager = DynamicToolManager(cache_ttl_seconds=300)  # Change this value

Logging Level

To change logging verbosity:

# In mcp_server.py
logging.basicConfig(
    level=logging.DEBUG,  # Change to DEBUG, INFO, WARNING, or ERROR
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

Testing

See TEST_SCENARIOS.md for comprehensive test scenarios including:

  • User-specific tool generation
  • Caching behavior
  • Tool execution
  • Error handling
  • Validation enforcement

API Schema Format

The external API should return a response with this structure:

{
  "fieldList": [
    {
      "name": "Subject",
      "paramName": "subject",
      "type": "TextFieldRest",
      "required": true,
      "description": "Request subject",
      "groupIds": [1, 2],
      "hidden": false,
      "removed": false,
      "inActive": false
    }
  ]
}

Supported field types:

  • TextFieldReststring
  • NumberFieldRestnumber
  • DropDownFieldReststring with enum
  • MultiSelectDropDownFieldRestarray of strings
  • And more (see api_client.py for full mapping)

Security Considerations

  • Authentication tokens are truncated in logs and responses
  • Tokens are validated on each request
  • No token = static tools only (graceful degradation)
  • FastMCP validates all tool arguments before execution

Troubleshooting

Server won't start

  • Check that all dependencies are installed: pip install -r requirements.txt
  • Verify Python version is 3.12+
  • Check logs for import errors

Tools not appearing

  • Verify Authorization header is present and correctly formatted
  • Check server logs for API fetch errors
  • Ensure external API is accessible
  • Verify user has permissions in the external system

Cache not updating

  • Default TTL is 5 minutes
  • Manually clear cache: Call tool_manager.clear_all_tools() or restart server
  • Check logs for cache hit/miss messages

License

[Your License Here]

Contributing

[Your Contributing Guidelines Here]

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选