Skip to content

feat: add custom tools support via add_tool() and custom_tools parameter#289

Open
nachogarcia wants to merge 1 commit intotadata-org:mainfrom
nachogarcia:main
Open

feat: add custom tools support via add_tool() and custom_tools parameter#289
nachogarcia wants to merge 1 commit intotadata-org:mainfrom
nachogarcia:main

Conversation

@nachogarcia
Copy link
Copy Markdown

Describe your changes

Adds a public API for registering custom MCP tools that don't map to FastAPI endpoints. This enables use cases like wrapping SSE streams, returning instructions, or bridging protocol gaps — without monkey-patching internal methods.

New API

from fastapi_mcp import FastApiMCP, HTTPRequestInfo
import mcp.types as types

# Option A: at construction time
mcp = FastApiMCP(
    app,
    custom_tools=[(my_tool, my_handler)],
)

# Option B: after construction, before mount
mcp.add_tool(my_tool, my_handler)

Handler signature:

async def my_handler(name, arguments, http_request_info, server):
    return [types.TextContent(type="text", text="response")]

Handlers receive the same HTTPRequestInfo (auth headers, cookies, etc.) that auto-generated tools get, plus the MCP Server instance for access to request_context.

What changed

  • fastapi_mcp/server.py: Added _custom_handlers dict, custom_tools constructor param, add_tool() method, and a dispatch branch in handle_call_tool that routes to custom handlers before falling through to _execute_api_tool
  • fastapi_mcp/__init__.py: Exported HTTPRequestInfo so consumers can type-hint handlers
  • tests/test_custom_tools.py: 7 new tests covering listing, calling, request info forwarding, server instance access, constructor param, OpenAPI tool coexistence, and error handling

~30 lines of new production code. No breaking changes — all existing behavior is preserved.

Issue ticket number and link (if applicable)

Closes #75

Checklist before requesting a review

  • Added relevant tests
  • Run ruff & mypy
  • All tests pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Adding custom tools

1 participant