From 73df4dcaeeba6f985607f633786d38db6caf23f7 Mon Sep 17 00:00:00 2001 From: "marvin-context-protocol[bot]" <225465937+marvin-context-protocol[bot]@users.noreply.github.com> Date: Thu, 14 May 2026 22:06:38 -0400 Subject: [PATCH] chore: Update SDK documentation (#4096) --- docs/python-sdk-pages.json | 355 +------ docs/python-sdk/fastmcp-apps-app.mdx | 146 --- docs/python-sdk/fastmcp-apps-approval.mdx | 58 -- docs/python-sdk/fastmcp-apps-choice.mdx | 44 - docs/python-sdk/fastmcp-apps-config.mdx | 90 -- docs/python-sdk/fastmcp-apps-file_upload.mdx | 144 --- docs/python-sdk/fastmcp-apps-form.mdx | 69 -- docs/python-sdk/fastmcp-apps-generative.mdx | 56 -- ...mcp-apps-__init__.mdx => fastmcp-apps.mdx} | 4 +- docs/python-sdk/fastmcp-cli-apps_dev.mdx | 47 - docs/python-sdk/fastmcp-cli-auth.mdx | 9 - docs/python-sdk/fastmcp-cli-cimd.mdx | 43 - docs/python-sdk/fastmcp-cli-cli.mdx | 146 --- docs/python-sdk/fastmcp-cli-client.mdx | 135 --- docs/python-sdk/fastmcp-cli-discovery.mdx | 71 -- docs/python-sdk/fastmcp-cli-generate.mdx | 66 -- .../fastmcp-cli-install-__init__.mdx | 9 - .../fastmcp-cli-install-claude_code.mdx | 71 -- .../fastmcp-cli-install-claude_desktop.mdx | 62 -- .../python-sdk/fastmcp-cli-install-cursor.mdx | 107 -- .../fastmcp-cli-install-gemini_cli.mdx | 68 -- docs/python-sdk/fastmcp-cli-install-goose.mdx | 67 -- .../fastmcp-cli-install-mcp_json.mdx | 49 - .../python-sdk/fastmcp-cli-install-shared.mdx | 62 -- docs/python-sdk/fastmcp-cli-install-stdio.mdx | 50 - docs/python-sdk/fastmcp-cli-run.mdx | 136 --- docs/python-sdk/fastmcp-cli-tasks.mdx | 41 - ...stmcp-cli-__init__.mdx => fastmcp-cli.mdx} | 4 +- .../fastmcp-client-auth-__init__.mdx | 8 - .../python-sdk/fastmcp-client-auth-bearer.mdx | 18 - docs/python-sdk/fastmcp-client-auth-oauth.mdx | 110 --- docs/python-sdk/fastmcp-client-client.mdx | 286 ------ .../python-sdk/fastmcp-client-elicitation.mdx | 18 - docs/python-sdk/fastmcp-client-logging.mdx | 24 - docs/python-sdk/fastmcp-client-messages.mdx | 107 -- .../fastmcp-client-mixins-__init__.mdx | 9 - .../fastmcp-client-mixins-prompts.mdx | 122 --- .../fastmcp-client-mixins-resources.mdx | 164 ---- .../fastmcp-client-mixins-task_management.mdx | 110 --- .../fastmcp-client-mixins-tools.mdx | 144 --- .../fastmcp-client-oauth_callback.mdx | 70 -- docs/python-sdk/fastmcp-client-progress.mdx | 25 - docs/python-sdk/fastmcp-client-roots.mdx | 20 - .../fastmcp-client-sampling-__init__.mdx | 14 - ...tmcp-client-sampling-handlers-__init__.mdx | 8 - ...mcp-client-sampling-handlers-anthropic.mdx | 17 - ...-client-sampling-handlers-google_genai.mdx | 17 - ...astmcp-client-sampling-handlers-openai.mdx | 17 - docs/python-sdk/fastmcp-client-tasks.mdx | 219 ----- docs/python-sdk/fastmcp-client-telemetry.mdx | 23 - .../fastmcp-client-transports-__init__.mdx | 8 - .../fastmcp-client-transports-base.mdx | 62 -- .../fastmcp-client-transports-config.mdx | 72 -- .../fastmcp-client-transports-http.mdx | 37 - .../fastmcp-client-transports-inference.mdx | 56 -- .../fastmcp-client-transports-memory.mdx | 27 - .../fastmcp-client-transports-sse.mdx | 25 - .../fastmcp-client-transports-stdio.mdx | 79 -- ...client-__init__.mdx => fastmcp-client.mdx} | 4 +- docs/python-sdk/fastmcp-decorators.mdx | 6 +- docs/python-sdk/fastmcp-exceptions.mdx | 22 +- ...tmcp-experimental-transforms-code_mode.mdx | 22 +- docs/python-sdk/fastmcp-mcp_config.mdx | 34 +- docs/python-sdk/fastmcp-prompts-base.mdx | 145 --- .../fastmcp-prompts-function_prompt.mdx | 103 -- ...ompts-__init__.mdx => fastmcp-prompts.mdx} | 4 +- docs/python-sdk/fastmcp-resources-base.mdx | 180 ---- .../fastmcp-resources-function_resource.mdx | 90 -- .../python-sdk/fastmcp-resources-template.mdx | 261 ----- docs/python-sdk/fastmcp-resources-types.mdx | 134 --- ...ces-__init__.mdx => fastmcp-resources.mdx} | 4 +- docs/python-sdk/fastmcp-server-app.mdx | 13 - docs/python-sdk/fastmcp-server-apps.mdx | 13 - .../fastmcp-server-auth-__init__.mdx | 8 - docs/python-sdk/fastmcp-server-auth-auth.mdx | 382 -------- .../fastmcp-server-auth-authorization.mdx | 129 --- docs/python-sdk/fastmcp-server-auth-cimd.mdx | 245 ----- .../fastmcp-server-auth-handlers-__init__.mdx | 8 - ...fastmcp-server-auth-handlers-authorize.mdx | 83 -- .../fastmcp-server-auth-jwt_issuer.mdx | 108 -- .../fastmcp-server-auth-middleware.mdx | 26 - ...stmcp-server-auth-oauth_proxy-__init__.mdx | 16 - ...astmcp-server-auth-oauth_proxy-consent.mdx | 28 - ...fastmcp-server-auth-oauth_proxy-models.mdx | 105 -- .../fastmcp-server-auth-oauth_proxy-proxy.mdx | 326 ------- .../fastmcp-server-auth-oauth_proxy-ui.mdx | 50 - .../fastmcp-server-auth-oidc_proxy.mdx | 82 -- ...fastmcp-server-auth-providers-__init__.mdx | 8 - .../fastmcp-server-auth-providers-auth0.mdx | 41 - .../fastmcp-server-auth-providers-aws.mdx | 87 -- .../fastmcp-server-auth-providers-azure.mdx | 221 ----- .../fastmcp-server-auth-providers-clerk.mdx | 94 -- .../fastmcp-server-auth-providers-debug.mdx | 70 -- .../fastmcp-server-auth-providers-descope.mdx | 60 -- .../fastmcp-server-auth-providers-discord.mdx | 66 -- .../fastmcp-server-auth-providers-github.mdx | 70 -- .../fastmcp-server-auth-providers-google.mdx | 74 -- ...astmcp-server-auth-providers-in_memory.mdx | 96 -- ...cp-server-auth-providers-introspection.mdx | 82 -- .../fastmcp-server-auth-providers-jwt.mdx | 146 --- ...fastmcp-server-auth-providers-keycloak.mdx | 20 - .../fastmcp-server-auth-providers-oci.mdx | 97 -- ...stmcp-server-auth-providers-propelauth.mdx | 69 -- ...fastmcp-server-auth-providers-scalekit.mdx | 61 -- ...fastmcp-server-auth-providers-supabase.mdx | 67 -- .../fastmcp-server-auth-providers-workos.mdx | 123 --- ...astmcp-server-auth-redirect_validation.mdx | 63 -- docs/python-sdk/fastmcp-server-auth-ssrf.mdx | 172 ---- docs/python-sdk/fastmcp-server-context.mdx | 755 -------------- .../fastmcp-server-dependencies.mdx | 576 ----------- .../python-sdk/fastmcp-server-elicitation.mdx | 152 --- .../python-sdk/fastmcp-server-event_store.mdx | 78 -- docs/python-sdk/fastmcp-server-http.mdx | 106 -- docs/python-sdk/fastmcp-server-lifespan.mdx | 101 -- docs/python-sdk/fastmcp-server-low_level.mdx | 108 -- .../fastmcp-server-middleware-__init__.mdx | 8 - ...astmcp-server-middleware-authorization.mdx | 116 --- .../fastmcp-server-middleware-caching.mdx | 225 ----- .../fastmcp-server-middleware-dereference.mdx | 35 - ...stmcp-server-middleware-error_handling.mdx | 60 -- .../fastmcp-server-middleware-logging.mdx | 58 -- .../fastmcp-server-middleware-middleware.mdx | 112 --- .../fastmcp-server-middleware-ping.mdx | 32 - ...astmcp-server-middleware-rate_limiting.mdx | 97 -- ...cp-server-middleware-response_limiting.mdx | 32 - .../fastmcp-server-middleware-timing.mdx | 105 -- ...stmcp-server-middleware-tool_injection.mdx | 97 -- .../fastmcp-server-mixins-__init__.mdx | 9 - .../fastmcp-server-mixins-lifespan.mdx | 30 - .../fastmcp-server-mixins-mcp_operations.mdx | 23 - .../fastmcp-server-mixins-transport.mdx | 131 --- .../fastmcp-server-openapi-__init__.mdx | 27 - .../fastmcp-server-openapi-components.mdx | 12 - .../fastmcp-server-openapi-routing.mdx | 13 - .../fastmcp-server-openapi-server.mdx | 43 - .../fastmcp-server-providers-__init__.mdx | 34 - .../fastmcp-server-providers-addressing.mdx | 81 -- .../fastmcp-server-providers-aggregate.mdx | 101 -- .../fastmcp-server-providers-base.mdx | 334 ------- ...tmcp-server-providers-fastmcp_provider.mdx | 256 ----- .../fastmcp-server-providers-filesystem.mdx | 54 - ...-server-providers-filesystem_discovery.mdx | 109 --- ...rver-providers-local_provider-__init__.mdx | 13 - ...ers-local_provider-decorators-__init__.mdx | 13 - ...ders-local_provider-decorators-prompts.mdx | 81 -- ...rs-local_provider-decorators-resources.mdx | 77 -- ...viders-local_provider-decorators-tools.mdx | 84 -- ...roviders-local_provider-local_provider.mdx | 125 --- ...tmcp-server-providers-openapi-__init__.mdx | 23 - ...cp-server-providers-openapi-components.mdx | 62 -- ...tmcp-server-providers-openapi-provider.mdx | 40 - ...stmcp-server-providers-openapi-routing.mdx | 23 - ...tmcp-server-providers-prefab_synthesis.mdx | 58 -- .../fastmcp-server-providers-proxy.mdx | 327 ------- ...stmcp-server-providers-skills-__init__.mdx | 32 - ...erver-providers-skills-claude_provider.mdx | 25 - ...er-providers-skills-directory_provider.mdx | 31 - ...server-providers-skills-skill_provider.mdx | 121 --- ...rver-providers-skills-vendor_providers.mdx | 56 -- ...tmcp-server-providers-wrapped_provider.mdx | 13 - docs/python-sdk/fastmcp-server-proxy.mdx | 14 - .../fastmcp-server-sampling-__init__.mdx | 9 - .../fastmcp-server-sampling-run.mdx | 203 ---- .../fastmcp-server-sampling-sampling_tool.mdx | 101 -- docs/python-sdk/fastmcp-server-server.mdx | 922 ------------------ .../fastmcp-server-tasks-__init__.mdx | 12 - .../fastmcp-server-tasks-capabilities.mdx | 33 - .../fastmcp-server-tasks-config.mdx | 96 -- .../fastmcp-server-tasks-context.mdx | 192 ---- .../fastmcp-server-tasks-elicitation.mdx | 96 -- .../fastmcp-server-tasks-handlers.mdx | 41 - docs/python-sdk/fastmcp-server-tasks-keys.mdx | 133 --- .../fastmcp-server-tasks-notifications.mdx | 113 --- .../fastmcp-server-tasks-requests.mdx | 91 -- .../fastmcp-server-tasks-routing.mdx | 37 - .../fastmcp-server-tasks-subscriptions.mdx | 38 - docs/python-sdk/fastmcp-server-telemetry.mdx | 56 -- .../fastmcp-server-transforms-__init__.mdx | 193 ---- .../fastmcp-server-transforms-catalog.mdx | 224 ----- .../fastmcp-server-transforms-namespace.mdx | 96 -- ...mcp-server-transforms-prompts_as_tools.mdx | 66 -- ...p-server-transforms-resources_as_tools.mdx | 66 -- ...tmcp-server-transforms-search-__init__.mdx | 23 - .../fastmcp-server-transforms-search-base.mdx | 105 -- .../fastmcp-server-transforms-search-bm25.mdx | 20 - ...fastmcp-server-transforms-search-regex.mdx | 20 - ...stmcp-server-transforms-tool_transform.mdx | 40 - ...stmcp-server-transforms-version_filter.mdx | 89 -- .../fastmcp-server-transforms-visibility.mdx | 261 ----- ...server-__init__.mdx => fastmcp-server.mdx} | 4 +- docs/python-sdk/fastmcp-settings.mdx | 10 +- docs/python-sdk/fastmcp-telemetry.mdx | 8 +- docs/python-sdk/fastmcp-tools-base.mdx | 116 --- .../fastmcp-tools-function_parsing.mdx | 21 - .../fastmcp-tools-function_tool.mdx | 108 -- .../fastmcp-tools-tool_transform.mdx | 308 ------ ...p-tools-__init__.mdx => fastmcp-tools.mdx} | 4 +- .../fastmcp-utilities-async_utils.mdx | 6 +- docs/python-sdk/fastmcp-utilities-auth.mdx | 6 +- docs/python-sdk/fastmcp-utilities-cli.mdx | 6 +- .../fastmcp-utilities-components.mdx | 24 +- .../fastmcp-utilities-docstring_parsing.mdx | 4 +- .../fastmcp-utilities-exceptions.mdx | 4 +- docs/python-sdk/fastmcp-utilities-http.mdx | 2 +- docs/python-sdk/fastmcp-utilities-inspect.mdx | 24 +- .../fastmcp-utilities-json_schema.mdx | 6 +- .../fastmcp-utilities-json_schema_type.mdx | 4 +- .../python-sdk/fastmcp-utilities-lifespan.mdx | 2 +- docs/python-sdk/fastmcp-utilities-logging.mdx | 6 +- ...mcp_server_config-v1-environments-base.mdx | 6 +- ...s-mcp_server_config-v1-environments-uv.mdx | 6 +- ...mcp_server_config-v1-mcp_server_config.mdx | 28 +- ...ties-mcp_server_config-v1-sources-base.mdx | 6 +- ...cp_server_config-v1-sources-filesystem.mdx | 6 +- docs/python-sdk/fastmcp-utilities-mime.mdx | 2 +- .../fastmcp-utilities-openapi-director.mdx | 36 - .../fastmcp-utilities-openapi-formatters.mdx | 96 -- ...tilities-openapi-json_schema_converter.mdx | 62 -- .../fastmcp-utilities-openapi-models.mdx | 35 - .../fastmcp-utilities-openapi-parser.mdx | 43 - .../fastmcp-utilities-openapi-schemas.mdx | 43 - ...it__.mdx => fastmcp-utilities-openapi.mdx} | 4 +- .../fastmcp-utilities-pagination.mdx | 8 +- docs/python-sdk/fastmcp-utilities-skills.mdx | 14 +- docs/python-sdk/fastmcp-utilities-tests.mdx | 12 +- docs/python-sdk/fastmcp-utilities-timeout.mdx | 4 +- .../fastmcp-utilities-token_cache.mdx | 8 +- docs/python-sdk/fastmcp-utilities-types.mdx | 32 +- docs/python-sdk/fastmcp-utilities-ui.mdx | 14 +- .../fastmcp-utilities-version_check.mdx | 4 +- .../python-sdk/fastmcp-utilities-versions.mdx | 22 +- 231 files changed, 208 insertions(+), 18203 deletions(-) delete mode 100644 docs/python-sdk/fastmcp-apps-app.mdx delete mode 100644 docs/python-sdk/fastmcp-apps-approval.mdx delete mode 100644 docs/python-sdk/fastmcp-apps-choice.mdx delete mode 100644 docs/python-sdk/fastmcp-apps-config.mdx delete mode 100644 docs/python-sdk/fastmcp-apps-file_upload.mdx delete mode 100644 docs/python-sdk/fastmcp-apps-form.mdx delete mode 100644 docs/python-sdk/fastmcp-apps-generative.mdx rename docs/python-sdk/{fastmcp-apps-__init__.mdx => fastmcp-apps.mdx} (89%) delete mode 100644 docs/python-sdk/fastmcp-cli-apps_dev.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-auth.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-cimd.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-cli.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-client.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-discovery.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-generate.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-claude_code.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-claude_desktop.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-cursor.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-gemini_cli.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-goose.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-mcp_json.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-shared.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-install-stdio.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-run.mdx delete mode 100644 docs/python-sdk/fastmcp-cli-tasks.mdx rename docs/python-sdk/{fastmcp-cli-__init__.mdx => fastmcp-cli.mdx} (55%) delete mode 100644 docs/python-sdk/fastmcp-client-auth-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-client-auth-bearer.mdx delete mode 100644 docs/python-sdk/fastmcp-client-auth-oauth.mdx delete mode 100644 docs/python-sdk/fastmcp-client-client.mdx delete mode 100644 docs/python-sdk/fastmcp-client-elicitation.mdx delete mode 100644 docs/python-sdk/fastmcp-client-logging.mdx delete mode 100644 docs/python-sdk/fastmcp-client-messages.mdx delete mode 100644 docs/python-sdk/fastmcp-client-mixins-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-client-mixins-prompts.mdx delete mode 100644 docs/python-sdk/fastmcp-client-mixins-resources.mdx delete mode 100644 docs/python-sdk/fastmcp-client-mixins-task_management.mdx delete mode 100644 docs/python-sdk/fastmcp-client-mixins-tools.mdx delete mode 100644 docs/python-sdk/fastmcp-client-oauth_callback.mdx delete mode 100644 docs/python-sdk/fastmcp-client-progress.mdx delete mode 100644 docs/python-sdk/fastmcp-client-roots.mdx delete mode 100644 docs/python-sdk/fastmcp-client-sampling-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-client-sampling-handlers-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-client-sampling-handlers-anthropic.mdx delete mode 100644 docs/python-sdk/fastmcp-client-sampling-handlers-google_genai.mdx delete mode 100644 docs/python-sdk/fastmcp-client-sampling-handlers-openai.mdx delete mode 100644 docs/python-sdk/fastmcp-client-tasks.mdx delete mode 100644 docs/python-sdk/fastmcp-client-telemetry.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-base.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-config.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-http.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-inference.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-memory.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-sse.mdx delete mode 100644 docs/python-sdk/fastmcp-client-transports-stdio.mdx rename docs/python-sdk/{fastmcp-client-__init__.mdx => fastmcp-client.mdx} (72%) delete mode 100644 docs/python-sdk/fastmcp-prompts-base.mdx delete mode 100644 docs/python-sdk/fastmcp-prompts-function_prompt.mdx rename docs/python-sdk/{fastmcp-prompts-__init__.mdx => fastmcp-prompts.mdx} (72%) delete mode 100644 docs/python-sdk/fastmcp-resources-base.mdx delete mode 100644 docs/python-sdk/fastmcp-resources-function_resource.mdx delete mode 100644 docs/python-sdk/fastmcp-resources-template.mdx delete mode 100644 docs/python-sdk/fastmcp-resources-types.mdx rename docs/python-sdk/{fastmcp-resources-__init__.mdx => fastmcp-resources.mdx} (72%) delete mode 100644 docs/python-sdk/fastmcp-server-app.mdx delete mode 100644 docs/python-sdk/fastmcp-server-apps.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-auth.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-authorization.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-cimd.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-handlers-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-handlers-authorize.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-jwt_issuer.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-middleware.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-oauth_proxy-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-oauth_proxy-consent.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-oauth_proxy-models.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-oauth_proxy-proxy.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-oauth_proxy-ui.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-oidc_proxy.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-auth0.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-aws.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-azure.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-clerk.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-debug.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-descope.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-discord.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-github.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-google.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-introspection.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-keycloak.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-oci.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-propelauth.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-scalekit.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-supabase.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-providers-workos.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-redirect_validation.mdx delete mode 100644 docs/python-sdk/fastmcp-server-auth-ssrf.mdx delete mode 100644 docs/python-sdk/fastmcp-server-context.mdx delete mode 100644 docs/python-sdk/fastmcp-server-dependencies.mdx delete mode 100644 docs/python-sdk/fastmcp-server-elicitation.mdx delete mode 100644 docs/python-sdk/fastmcp-server-event_store.mdx delete mode 100644 docs/python-sdk/fastmcp-server-http.mdx delete mode 100644 docs/python-sdk/fastmcp-server-lifespan.mdx delete mode 100644 docs/python-sdk/fastmcp-server-low_level.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-authorization.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-caching.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-dereference.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-error_handling.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-logging.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-middleware.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-ping.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-rate_limiting.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-response_limiting.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-timing.mdx delete mode 100644 docs/python-sdk/fastmcp-server-middleware-tool_injection.mdx delete mode 100644 docs/python-sdk/fastmcp-server-mixins-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-mixins-lifespan.mdx delete mode 100644 docs/python-sdk/fastmcp-server-mixins-mcp_operations.mdx delete mode 100644 docs/python-sdk/fastmcp-server-mixins-transport.mdx delete mode 100644 docs/python-sdk/fastmcp-server-openapi-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-openapi-components.mdx delete mode 100644 docs/python-sdk/fastmcp-server-openapi-routing.mdx delete mode 100644 docs/python-sdk/fastmcp-server-openapi-server.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-addressing.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-aggregate.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-base.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-fastmcp_provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-filesystem.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-filesystem_discovery.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-local_provider-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-local_provider-decorators-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-local_provider-decorators-prompts.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-local_provider-decorators-resources.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-local_provider-decorators-tools.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-local_provider-local_provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-openapi-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-openapi-components.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-openapi-provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-openapi-routing.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-prefab_synthesis.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-proxy.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-skills-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-skills-claude_provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-skills-directory_provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-skills-skill_provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-skills-vendor_providers.mdx delete mode 100644 docs/python-sdk/fastmcp-server-providers-wrapped_provider.mdx delete mode 100644 docs/python-sdk/fastmcp-server-proxy.mdx delete mode 100644 docs/python-sdk/fastmcp-server-sampling-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-sampling-run.mdx delete mode 100644 docs/python-sdk/fastmcp-server-sampling-sampling_tool.mdx delete mode 100644 docs/python-sdk/fastmcp-server-server.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-capabilities.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-config.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-context.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-elicitation.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-handlers.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-keys.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-notifications.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-requests.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-routing.mdx delete mode 100644 docs/python-sdk/fastmcp-server-tasks-subscriptions.mdx delete mode 100644 docs/python-sdk/fastmcp-server-telemetry.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-catalog.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-namespace.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-prompts_as_tools.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-resources_as_tools.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-search-__init__.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-search-base.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-search-bm25.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-search-regex.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-tool_transform.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-version_filter.mdx delete mode 100644 docs/python-sdk/fastmcp-server-transforms-visibility.mdx rename docs/python-sdk/{fastmcp-server-__init__.mdx => fastmcp-server.mdx} (72%) delete mode 100644 docs/python-sdk/fastmcp-tools-base.mdx delete mode 100644 docs/python-sdk/fastmcp-tools-function_parsing.mdx delete mode 100644 docs/python-sdk/fastmcp-tools-function_tool.mdx delete mode 100644 docs/python-sdk/fastmcp-tools-tool_transform.mdx rename docs/python-sdk/{fastmcp-tools-__init__.mdx => fastmcp-tools.mdx} (72%) delete mode 100644 docs/python-sdk/fastmcp-utilities-openapi-director.mdx delete mode 100644 docs/python-sdk/fastmcp-utilities-openapi-formatters.mdx delete mode 100644 docs/python-sdk/fastmcp-utilities-openapi-json_schema_converter.mdx delete mode 100644 docs/python-sdk/fastmcp-utilities-openapi-models.mdx delete mode 100644 docs/python-sdk/fastmcp-utilities-openapi-parser.mdx delete mode 100644 docs/python-sdk/fastmcp-utilities-openapi-schemas.mdx rename docs/python-sdk/{fastmcp-utilities-openapi-__init__.mdx => fastmcp-utilities-openapi.mdx} (74%) diff --git a/docs/python-sdk-pages.json b/docs/python-sdk-pages.json index 86cfabc6b..704b28e4f 100644 --- a/docs/python-sdk-pages.json +++ b/docs/python-sdk-pages.json @@ -1,114 +1,18 @@ [ + "python-sdk/fastmcp-apps", + "python-sdk/fastmcp-cli", + "python-sdk/fastmcp-client", "python-sdk/fastmcp-decorators", "python-sdk/fastmcp-dependencies", "python-sdk/fastmcp-exceptions", "python-sdk/fastmcp-mcp_config", + "python-sdk/fastmcp-prompts", + "python-sdk/fastmcp-resources", + "python-sdk/fastmcp-server", "python-sdk/fastmcp-settings", "python-sdk/fastmcp-telemetry", + "python-sdk/fastmcp-tools", "python-sdk/fastmcp-types", - { - "group": "fastmcp.apps", - "pages": [ - "python-sdk/fastmcp-apps-__init__", - "python-sdk/fastmcp-apps-app", - "python-sdk/fastmcp-apps-approval", - "python-sdk/fastmcp-apps-choice", - "python-sdk/fastmcp-apps-config", - "python-sdk/fastmcp-apps-file_upload", - "python-sdk/fastmcp-apps-form", - "python-sdk/fastmcp-apps-generative" - ] - }, - { - "group": "fastmcp.cli", - "pages": [ - "python-sdk/fastmcp-cli-__init__", - "python-sdk/fastmcp-cli-apps_dev", - "python-sdk/fastmcp-cli-auth", - "python-sdk/fastmcp-cli-cimd", - "python-sdk/fastmcp-cli-cli", - "python-sdk/fastmcp-cli-client", - "python-sdk/fastmcp-cli-discovery", - "python-sdk/fastmcp-cli-generate", - { - "group": "install", - "pages": [ - "python-sdk/fastmcp-cli-install-__init__", - "python-sdk/fastmcp-cli-install-claude_code", - "python-sdk/fastmcp-cli-install-claude_desktop", - "python-sdk/fastmcp-cli-install-cursor", - "python-sdk/fastmcp-cli-install-gemini_cli", - "python-sdk/fastmcp-cli-install-goose", - "python-sdk/fastmcp-cli-install-mcp_json", - "python-sdk/fastmcp-cli-install-shared", - "python-sdk/fastmcp-cli-install-stdio" - ] - }, - "python-sdk/fastmcp-cli-run", - "python-sdk/fastmcp-cli-tasks" - ] - }, - { - "group": "fastmcp.client", - "pages": [ - "python-sdk/fastmcp-client-__init__", - { - "group": "auth", - "pages": [ - "python-sdk/fastmcp-client-auth-__init__", - "python-sdk/fastmcp-client-auth-bearer", - "python-sdk/fastmcp-client-auth-oauth" - ] - }, - "python-sdk/fastmcp-client-client", - "python-sdk/fastmcp-client-elicitation", - "python-sdk/fastmcp-client-logging", - "python-sdk/fastmcp-client-messages", - { - "group": "mixins", - "pages": [ - "python-sdk/fastmcp-client-mixins-__init__", - "python-sdk/fastmcp-client-mixins-prompts", - "python-sdk/fastmcp-client-mixins-resources", - "python-sdk/fastmcp-client-mixins-task_management", - "python-sdk/fastmcp-client-mixins-tools" - ] - }, - "python-sdk/fastmcp-client-oauth_callback", - "python-sdk/fastmcp-client-progress", - "python-sdk/fastmcp-client-roots", - { - "group": "sampling", - "pages": [ - "python-sdk/fastmcp-client-sampling-__init__", - { - "group": "handlers", - "pages": [ - "python-sdk/fastmcp-client-sampling-handlers-__init__", - "python-sdk/fastmcp-client-sampling-handlers-anthropic", - "python-sdk/fastmcp-client-sampling-handlers-google_genai", - "python-sdk/fastmcp-client-sampling-handlers-openai" - ] - } - ] - }, - "python-sdk/fastmcp-client-tasks", - "python-sdk/fastmcp-client-telemetry", - { - "group": "transports", - "pages": [ - "python-sdk/fastmcp-client-transports-__init__", - "python-sdk/fastmcp-client-transports-base", - "python-sdk/fastmcp-client-transports-config", - "python-sdk/fastmcp-client-transports-http", - "python-sdk/fastmcp-client-transports-inference", - "python-sdk/fastmcp-client-transports-memory", - "python-sdk/fastmcp-client-transports-sse", - "python-sdk/fastmcp-client-transports-stdio" - ] - } - ] - }, { "group": "fastmcp.experimental", "pages": [ @@ -129,238 +33,6 @@ } ] }, - { - "group": "fastmcp.prompts", - "pages": [ - "python-sdk/fastmcp-prompts-__init__", - "python-sdk/fastmcp-prompts-base", - "python-sdk/fastmcp-prompts-function_prompt" - ] - }, - { - "group": "fastmcp.resources", - "pages": [ - "python-sdk/fastmcp-resources-__init__", - "python-sdk/fastmcp-resources-base", - "python-sdk/fastmcp-resources-function_resource", - "python-sdk/fastmcp-resources-template", - "python-sdk/fastmcp-resources-types" - ] - }, - { - "group": "fastmcp.server", - "pages": [ - "python-sdk/fastmcp-server-__init__", - "python-sdk/fastmcp-server-app", - "python-sdk/fastmcp-server-apps", - { - "group": "auth", - "pages": [ - "python-sdk/fastmcp-server-auth-__init__", - "python-sdk/fastmcp-server-auth-auth", - "python-sdk/fastmcp-server-auth-authorization", - "python-sdk/fastmcp-server-auth-cimd", - { - "group": "handlers", - "pages": [ - "python-sdk/fastmcp-server-auth-handlers-__init__", - "python-sdk/fastmcp-server-auth-handlers-authorize" - ] - }, - "python-sdk/fastmcp-server-auth-jwt_issuer", - "python-sdk/fastmcp-server-auth-middleware", - { - "group": "oauth_proxy", - "pages": [ - "python-sdk/fastmcp-server-auth-oauth_proxy-__init__", - "python-sdk/fastmcp-server-auth-oauth_proxy-consent", - "python-sdk/fastmcp-server-auth-oauth_proxy-models", - "python-sdk/fastmcp-server-auth-oauth_proxy-proxy", - "python-sdk/fastmcp-server-auth-oauth_proxy-ui" - ] - }, - "python-sdk/fastmcp-server-auth-oidc_proxy", - { - "group": "providers", - "pages": [ - "python-sdk/fastmcp-server-auth-providers-__init__", - "python-sdk/fastmcp-server-auth-providers-auth0", - "python-sdk/fastmcp-server-auth-providers-aws", - "python-sdk/fastmcp-server-auth-providers-azure", - "python-sdk/fastmcp-server-auth-providers-clerk", - "python-sdk/fastmcp-server-auth-providers-debug", - "python-sdk/fastmcp-server-auth-providers-descope", - "python-sdk/fastmcp-server-auth-providers-discord", - "python-sdk/fastmcp-server-auth-providers-github", - "python-sdk/fastmcp-server-auth-providers-google", - "python-sdk/fastmcp-server-auth-providers-in_memory", - "python-sdk/fastmcp-server-auth-providers-introspection", - "python-sdk/fastmcp-server-auth-providers-jwt", - "python-sdk/fastmcp-server-auth-providers-keycloak", - "python-sdk/fastmcp-server-auth-providers-oci", - "python-sdk/fastmcp-server-auth-providers-propelauth", - "python-sdk/fastmcp-server-auth-providers-scalekit", - "python-sdk/fastmcp-server-auth-providers-supabase", - "python-sdk/fastmcp-server-auth-providers-workos" - ] - }, - "python-sdk/fastmcp-server-auth-redirect_validation", - "python-sdk/fastmcp-server-auth-ssrf" - ] - }, - "python-sdk/fastmcp-server-context", - "python-sdk/fastmcp-server-dependencies", - "python-sdk/fastmcp-server-elicitation", - "python-sdk/fastmcp-server-event_store", - "python-sdk/fastmcp-server-http", - "python-sdk/fastmcp-server-lifespan", - "python-sdk/fastmcp-server-low_level", - { - "group": "middleware", - "pages": [ - "python-sdk/fastmcp-server-middleware-__init__", - "python-sdk/fastmcp-server-middleware-authorization", - "python-sdk/fastmcp-server-middleware-caching", - "python-sdk/fastmcp-server-middleware-dereference", - "python-sdk/fastmcp-server-middleware-error_handling", - "python-sdk/fastmcp-server-middleware-logging", - "python-sdk/fastmcp-server-middleware-middleware", - "python-sdk/fastmcp-server-middleware-ping", - "python-sdk/fastmcp-server-middleware-rate_limiting", - "python-sdk/fastmcp-server-middleware-response_limiting", - "python-sdk/fastmcp-server-middleware-timing", - "python-sdk/fastmcp-server-middleware-tool_injection" - ] - }, - { - "group": "mixins", - "pages": [ - "python-sdk/fastmcp-server-mixins-__init__", - "python-sdk/fastmcp-server-mixins-lifespan", - "python-sdk/fastmcp-server-mixins-mcp_operations", - "python-sdk/fastmcp-server-mixins-transport" - ] - }, - { - "group": "openapi", - "pages": [ - "python-sdk/fastmcp-server-openapi-__init__", - "python-sdk/fastmcp-server-openapi-components", - "python-sdk/fastmcp-server-openapi-routing", - "python-sdk/fastmcp-server-openapi-server" - ] - }, - { - "group": "providers", - "pages": [ - "python-sdk/fastmcp-server-providers-__init__", - "python-sdk/fastmcp-server-providers-addressing", - "python-sdk/fastmcp-server-providers-aggregate", - "python-sdk/fastmcp-server-providers-base", - "python-sdk/fastmcp-server-providers-fastmcp_provider", - "python-sdk/fastmcp-server-providers-filesystem", - "python-sdk/fastmcp-server-providers-filesystem_discovery", - { - "group": "local_provider", - "pages": [ - "python-sdk/fastmcp-server-providers-local_provider-__init__", - { - "group": "decorators", - "pages": [ - "python-sdk/fastmcp-server-providers-local_provider-decorators-__init__", - "python-sdk/fastmcp-server-providers-local_provider-decorators-prompts", - "python-sdk/fastmcp-server-providers-local_provider-decorators-resources", - "python-sdk/fastmcp-server-providers-local_provider-decorators-tools" - ] - }, - "python-sdk/fastmcp-server-providers-local_provider-local_provider" - ] - }, - { - "group": "openapi", - "pages": [ - "python-sdk/fastmcp-server-providers-openapi-__init__", - "python-sdk/fastmcp-server-providers-openapi-components", - "python-sdk/fastmcp-server-providers-openapi-provider", - "python-sdk/fastmcp-server-providers-openapi-routing" - ] - }, - "python-sdk/fastmcp-server-providers-prefab_synthesis", - "python-sdk/fastmcp-server-providers-proxy", - { - "group": "skills", - "pages": [ - "python-sdk/fastmcp-server-providers-skills-__init__", - "python-sdk/fastmcp-server-providers-skills-claude_provider", - "python-sdk/fastmcp-server-providers-skills-directory_provider", - "python-sdk/fastmcp-server-providers-skills-skill_provider", - "python-sdk/fastmcp-server-providers-skills-vendor_providers" - ] - }, - "python-sdk/fastmcp-server-providers-wrapped_provider" - ] - }, - "python-sdk/fastmcp-server-proxy", - { - "group": "sampling", - "pages": [ - "python-sdk/fastmcp-server-sampling-__init__", - "python-sdk/fastmcp-server-sampling-run", - "python-sdk/fastmcp-server-sampling-sampling_tool" - ] - }, - "python-sdk/fastmcp-server-server", - { - "group": "tasks", - "pages": [ - "python-sdk/fastmcp-server-tasks-__init__", - "python-sdk/fastmcp-server-tasks-capabilities", - "python-sdk/fastmcp-server-tasks-config", - "python-sdk/fastmcp-server-tasks-context", - "python-sdk/fastmcp-server-tasks-elicitation", - "python-sdk/fastmcp-server-tasks-handlers", - "python-sdk/fastmcp-server-tasks-keys", - "python-sdk/fastmcp-server-tasks-notifications", - "python-sdk/fastmcp-server-tasks-requests", - "python-sdk/fastmcp-server-tasks-routing", - "python-sdk/fastmcp-server-tasks-subscriptions" - ] - }, - "python-sdk/fastmcp-server-telemetry", - { - "group": "transforms", - "pages": [ - "python-sdk/fastmcp-server-transforms-__init__", - "python-sdk/fastmcp-server-transforms-catalog", - "python-sdk/fastmcp-server-transforms-namespace", - "python-sdk/fastmcp-server-transforms-prompts_as_tools", - "python-sdk/fastmcp-server-transforms-resources_as_tools", - { - "group": "search", - "pages": [ - "python-sdk/fastmcp-server-transforms-search-__init__", - "python-sdk/fastmcp-server-transforms-search-base", - "python-sdk/fastmcp-server-transforms-search-bm25", - "python-sdk/fastmcp-server-transforms-search-regex" - ] - }, - "python-sdk/fastmcp-server-transforms-tool_transform", - "python-sdk/fastmcp-server-transforms-version_filter", - "python-sdk/fastmcp-server-transforms-visibility" - ] - } - ] - }, - { - "group": "fastmcp.tools", - "pages": [ - "python-sdk/fastmcp-tools-__init__", - "python-sdk/fastmcp-tools-base", - "python-sdk/fastmcp-tools-function_parsing", - "python-sdk/fastmcp-tools-function_tool", - "python-sdk/fastmcp-tools-tool_transform" - ] - }, { "group": "fastmcp.utilities", "pages": [ @@ -407,18 +79,7 @@ ] }, "python-sdk/fastmcp-utilities-mime", - { - "group": "openapi", - "pages": [ - "python-sdk/fastmcp-utilities-openapi-__init__", - "python-sdk/fastmcp-utilities-openapi-director", - "python-sdk/fastmcp-utilities-openapi-formatters", - "python-sdk/fastmcp-utilities-openapi-json_schema_converter", - "python-sdk/fastmcp-utilities-openapi-models", - "python-sdk/fastmcp-utilities-openapi-parser", - "python-sdk/fastmcp-utilities-openapi-schemas" - ] - }, + "python-sdk/fastmcp-utilities-openapi", "python-sdk/fastmcp-utilities-pagination", "python-sdk/fastmcp-utilities-skills", "python-sdk/fastmcp-utilities-tests", diff --git a/docs/python-sdk/fastmcp-apps-app.mdx b/docs/python-sdk/fastmcp-apps-app.mdx deleted file mode 100644 index e6053277e..000000000 --- a/docs/python-sdk/fastmcp-apps-app.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: app -sidebarTitle: app ---- - -# `fastmcp.apps.app` - - -FastMCPApp — a Provider that represents a composable MCP application. - -FastMCPApp binds entry-point tools (model calls these) together with backend -tools (the UI calls these via CallTool). Backend tools are tagged with -``meta["fastmcp"]["app"]`` so they can be found through the provider chain -even when transforms (namespace, visibility, etc.) have renamed or hidden -them — the server sets a context var that tells ``Provider.get_tool`` to -fall back to a direct lookup for app-visible tools. - -Usage:: - - from fastmcp import FastMCP, FastMCPApp - - app = FastMCPApp("Dashboard") - - @app.ui() - def show_dashboard() -> Component: - return Column(...) - - @app.tool() - def save_contact(name: str, email: str) -> str: - return name - - server = FastMCP("Platform") - server.add_provider(app) - - -## Classes - -### `FastMCPApp` - - -A Provider that represents an MCP application. - -Binds together entry-point tools (``@app.ui``), backend tools -(``@app.tool``), and the Prefab renderer resource. Backend tools -are tagged with ``meta["fastmcp"]["app"]`` so ``Provider.get_tool`` -can find them by original name even when transforms have been applied. - - -**Methods:** - -#### `tool` - -```python -tool(self, name_or_fn: F) -> F -``` - -#### `tool` - -```python -tool(self, name_or_fn: str | None = None) -> Callable[[F], F] -``` - -#### `tool` - -```python -tool(self, name_or_fn: str | AnyFunction | None = None) -> Any -``` - -Register a backend tool that the UI calls via CallTool. - -Backend tools default to ``visibility=["app"]``. Pass ``model=True`` -to also expose the tool to the model (``visibility=["app", "model"]``). - -Supports multiple calling patterns:: - - @app.tool - def save(name: str): ... - - @app.tool() - def save(name: str): ... - - @app.tool("custom_name") - def save(name: str): ... - - -#### `ui` - -```python -ui(self, name_or_fn: F) -> F -``` - -#### `ui` - -```python -ui(self, name_or_fn: str | None = None) -> Callable[[F], F] -``` - -#### `ui` - -```python -ui(self, name_or_fn: str | AnyFunction | None = None) -> Any -``` - -Register a UI entry-point tool that the model calls. - -Entry-point tools default to ``visibility=["model"]`` and auto-wire -the Prefab renderer resource and CSP. They are tagged with the app -name so structured content includes ``_meta.fastmcp.app``. - -Supports multiple calling patterns:: - - @app.ui - def dashboard() -> Component: ... - - @app.ui() - def dashboard() -> Component: ... - - @app.ui("my_dashboard") - def dashboard() -> Component: ... - - -#### `add_tool` - -```python -add_tool(self, tool: Tool | Callable[..., Any]) -> Tool -``` - -Add a tool to this app programmatically. - -The tool is tagged with this app's name for routing. - - -#### `lifespan` - -```python -lifespan(self) -> AsyncIterator[None] -``` - -#### `run` - -```python -run(self, transport: Literal['stdio', 'http', 'sse', 'streamable-http'] | None = None, **kwargs: Any) -> None -``` - -Create a temporary FastMCP server and run this app standalone. - diff --git a/docs/python-sdk/fastmcp-apps-approval.mdx b/docs/python-sdk/fastmcp-apps-approval.mdx deleted file mode 100644 index 461a55c52..000000000 --- a/docs/python-sdk/fastmcp-apps-approval.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: approval -sidebarTitle: approval ---- - -# `fastmcp.apps.approval` - - -Approval — a Provider that adds human-in-the-loop approval to any server. - -The LLM presents a summary of what it's about to do, and the user -approves or rejects via buttons. The result is sent back into the -conversation as a message, prompting the LLM's next turn. - -Requires ``fastmcp[apps]`` (prefab-ui). - -Usage:: - - from fastmcp import FastMCP - from fastmcp.apps.approval import Approval - - mcp = FastMCP("My Server") - mcp.add_provider(Approval()) - - -## Classes - -### `Approval` - - -A Provider that adds human-in-the-loop approval to a server. - -The LLM calls the ``request_approval`` tool with a summary and -optional details. The user sees an approval card with Approve and -Reject buttons. Clicking either sends a message back into the -conversation (via ``SendMessage``), triggering the LLM's next turn. - -The message appears as if the user sent it, so the LLM sees -something like ``'"Deploy v3.2 to production" is APPROVED'``. - -Example:: - - from fastmcp import FastMCP - from fastmcp.apps.approval import Approval - - mcp = FastMCP("My Server") - mcp.add_provider(Approval()) - -Customized:: - - Approval( - title="Deploy Gate", - approve_text="Ship it", - approve_variant="default", - reject_text="Abort", - reject_variant="destructive", - ) - diff --git a/docs/python-sdk/fastmcp-apps-choice.mdx b/docs/python-sdk/fastmcp-apps-choice.mdx deleted file mode 100644 index 4f693f898..000000000 --- a/docs/python-sdk/fastmcp-apps-choice.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: choice -sidebarTitle: choice ---- - -# `fastmcp.apps.choice` - - -Choice — a Provider that lets the user pick from a set of options. - -The LLM presents options, the user clicks one, and the selection -flows back into the conversation as a message. - -Requires ``fastmcp[apps]`` (prefab-ui). - -Usage:: - - from fastmcp import FastMCP - from fastmcp.apps.choice import Choice - - mcp = FastMCP("My Server") - mcp.add_provider(Choice()) - - -## Classes - -### `Choice` - - -A Provider that lets the user choose from a set of options. - -The LLM calls ``choose`` with a prompt and a list of options. -The user sees a card with one button per option. Clicking a button -sends the selection back into the conversation via ``SendMessage``, -triggering the LLM's next turn. - -Example:: - - from fastmcp import FastMCP - from fastmcp.apps.choice import Choice - - mcp = FastMCP("My Server") - mcp.add_provider(Choice()) - diff --git a/docs/python-sdk/fastmcp-apps-config.mdx b/docs/python-sdk/fastmcp-apps-config.mdx deleted file mode 100644 index d7c5edf2f..000000000 --- a/docs/python-sdk/fastmcp-apps-config.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: config -sidebarTitle: config ---- - -# `fastmcp.apps.config` - - -MCP Apps support — extension negotiation and typed UI metadata models. - -Provides constants and Pydantic models for the MCP Apps extension -(io.modelcontextprotocol/ui), enabling tools and resources to carry -UI metadata for clients that support interactive app rendering. - - -## Functions - -### `app_config_to_meta_dict` - -```python -app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any] -``` - - -Convert an AppConfig or dict to the wire-format dict for ``meta["ui"]``. - - -## Classes - -### `ResourceCSP` - - -Content Security Policy for MCP App resources. - -Declares which external origins the app is allowed to connect to or -load resources from. Hosts use these declarations to build the -``Content-Security-Policy`` header for the sandboxed iframe. - - -### `ResourcePermissions` - - -Iframe sandbox permissions for MCP App resources. - -Each field, when set (typically to ``{}``), requests that the host -grant the corresponding Permission Policy feature to the sandboxed -iframe. Hosts MAY honour these; apps should use JS feature detection -as a fallback. - - -### `AppConfig` - - -Configuration for MCP App tools and resources. - -Controls how a tool or resource participates in the MCP Apps extension. -On tools, ``resource_uri`` and ``visibility`` specify which UI resource -to render and where the tool appears. On resources, those fields must -be left unset (the resource itself is the UI). - -All fields use ``exclude_none`` serialization so only explicitly-set -values appear on the wire. Aliases match the MCP Apps wire format -(camelCase). - - -### `PrefabAppConfig` - - -App configuration for Prefab tools with sensible defaults. - -Like ``app=True`` but customizable. Auto-wires the Prefab renderer -URI and merges the renderer's CSP with any additional domains you -specify. The renderer resource is registered automatically. - -Example:: - - @mcp.tool(app=PrefabAppConfig()) # same as app=True - - @mcp.tool(app=PrefabAppConfig( - csp=ResourceCSP(frame_domains=["https://example.com"]), - )) - - -**Methods:** - -#### `model_post_init` - -```python -model_post_init(self, __context: Any) -> None -``` diff --git a/docs/python-sdk/fastmcp-apps-file_upload.mdx b/docs/python-sdk/fastmcp-apps-file_upload.mdx deleted file mode 100644 index a77d9fa6a..000000000 --- a/docs/python-sdk/fastmcp-apps-file_upload.mdx +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: file_upload -sidebarTitle: file_upload ---- - -# `fastmcp.apps.file_upload` - - -FileUpload — a Provider that adds drag-and-drop file upload to any server. - -Lets users upload files directly to the server through an interactive UI, -bypassing the LLM context window entirely. The LLM can then read and work -with uploaded files through model-visible tools. - -Requires ``fastmcp[apps]`` (prefab-ui). - -Usage:: - - from fastmcp import FastMCP - from fastmcp.apps import FileUpload - - mcp = FastMCP("My Server") - mcp.add_provider(FileUpload()) - -For custom persistence, override the storage methods:: - - class S3Upload(FileUpload): - def on_store(self, files, ctx): - # write to S3, return summaries - ... - - def on_list(self, ctx): - # list from S3 - ... - - def on_read(self, name, ctx): - # read from S3 - ... - - -## Classes - -### `FileUpload` - - -A Provider that adds file upload capabilities to a server. - -Registers a drag-and-drop UI tool, a backend storage tool, and -model-visible tools for listing and reading uploaded files. - -Files are scoped by MCP session and stored in memory by default. -Override ``on_store``, ``on_list``, and ``on_read`` for custom -persistence (filesystem, S3, database, etc.). Each method receives -the current ``Context``, giving access to session ID, auth tokens, -and request metadata for partitioning and authorization. - -**Session scoping:** The default storage uses ``ctx.session_id`` to -isolate files by session. This works with stdio, SSE, and stateful -HTTP transports. In **stateless HTTP** mode, each request creates a -new session, so files won't persist across requests. For stateless -deployments, override the storage methods to partition by a stable -identifier from the auth context:: - - class UserScopedUpload(FileUpload): - def on_store(self, files, ctx): - user_id = ctx.access_token["sub"] - ... - -Example:: - - from fastmcp import FastMCP - from fastmcp.apps.file_upload import FileUpload - - mcp = FastMCP("My Server") - mcp.add_provider(FileUpload()) - - -**Methods:** - -#### `on_store` - -```python -on_store(self, files: list[dict[str, Any]], ctx: Context) -> list[dict[str, Any]] -``` - -Store uploaded files and return summaries. - -**Args:** -- `files`: List of file dicts, each with ``name``, ``size``, -``type``, and ``data`` (base64-encoded content). -- `ctx`: The current request context. Use for session ID, -auth tokens, or any metadata needed for partitioning. - -Override this method for custom persistence. The default -implementation stores files in memory, scoped by -``_get_scope_key(ctx)``. - -**Returns:** -- List of file summary dicts (``name``, ``type``, ``size``, -- ``size_display``, ``uploaded_at``). - - -#### `on_list` - -```python -on_list(self, ctx: Context) -> list[dict[str, Any]] -``` - -List all stored files. - -**Args:** -- `ctx`: The current request context. - -Override this method for custom persistence. The default -implementation returns files from the current scope. - -**Returns:** -- List of file summary dicts. - - -#### `on_read` - -```python -on_read(self, name: str, ctx: Context) -> dict[str, Any] -``` - -Read a file's contents by name. - -**Args:** -- `name`: The filename to read. -- `ctx`: The current request context. - -Override this method for custom persistence. The default -implementation reads from the current scope's in-memory store. -Text files are decoded from base64; binary files return a -truncated base64 preview. - -**Returns:** -- Dict with file metadata and ``content`` (text) or -- ``content_base64`` (binary preview). - -**Raises:** -- `ValueError`: If the file is not found. - diff --git a/docs/python-sdk/fastmcp-apps-form.mdx b/docs/python-sdk/fastmcp-apps-form.mdx deleted file mode 100644 index 1f7b5c478..000000000 --- a/docs/python-sdk/fastmcp-apps-form.mdx +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: form -sidebarTitle: form ---- - -# `fastmcp.apps.form` - - -FormInput — a Provider that collects structured input from the user. - -Define a Pydantic model for the data you need, and ``FormInput`` -generates a form UI. The user fills it out, the submission is -validated, and an optional callback processes the result. - -Requires ``fastmcp[apps]`` (prefab-ui). - -Usage:: - - from pydantic import BaseModel - from fastmcp import FastMCP - from fastmcp.apps.form import FormInput - - class ShippingAddress(BaseModel): - street: str - city: str - state: str - zip_code: str - - mcp = FastMCP("My Server") - mcp.add_provider(FormInput(model=ShippingAddress)) - - -## Classes - -### `FormInput` - - -A Provider that collects structured input via a Pydantic model. - -Define a model for the data you need, and ``FormInput`` generates -a form from it using ``Form.from_model()``. Field types, labels, -descriptions, and validation are all derived from the model. - -Optionally provide an ``on_submit`` callback to process the -validated data. The callback receives a model instance and returns -a string that goes back to the LLM. Without a callback, the -validated JSON is sent directly. - -Example:: - - from pydantic import BaseModel - from fastmcp import FastMCP - from fastmcp.apps.form import FormInput - - class Contact(BaseModel): - name: str - email: str - - mcp = FastMCP("My Server") - mcp.add_provider(FormInput(model=Contact)) - -With a callback:: - - def save_contact(contact: Contact) -> str: - db.insert(contact.model_dump()) - return f"Saved {contact.name}" - - mcp.add_provider(FormInput(model=Contact, on_submit=save_contact)) - diff --git a/docs/python-sdk/fastmcp-apps-generative.mdx b/docs/python-sdk/fastmcp-apps-generative.mdx deleted file mode 100644 index 336d4f353..000000000 --- a/docs/python-sdk/fastmcp-apps-generative.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: generative -sidebarTitle: generative ---- - -# `fastmcp.apps.generative` - - -GenerativeUI — a Provider that adds LLM-generated UI capabilities. - -Registers tools and resources from ``prefab_ui.generative`` so that an -LLM can write Prefab Python code, execute it in a sandbox, and render -the result as a streaming interactive UI. - -Requires ``fastmcp[apps]`` (prefab-ui). - -Usage:: - - from fastmcp import FastMCP - from fastmcp.apps.generative import GenerativeUI - - mcp = FastMCP("My Server") - mcp.add_provider(GenerativeUI()) - - -## Classes - -### `GenerativeUI` - - -A Provider that adds generative UI capabilities to a server. - -Registers: - -- A ``generate_ui`` tool that accepts Prefab Python code, executes - it in a Pyodide sandbox, and returns the rendered PrefabApp. - Supports streaming via ``ontoolinputpartial``. -- A ``components`` tool that searches the Prefab component library. -- The generative renderer resource with CSP for Pyodide CDN access. - -Example:: - - from fastmcp import FastMCP - from fastmcp.apps.generative import GenerativeUI - - mcp = FastMCP("My Server") - mcp.add_provider(GenerativeUI()) - - -**Methods:** - -#### `lifespan` - -```python -lifespan(self) -> AsyncIterator[None] -``` diff --git a/docs/python-sdk/fastmcp-apps-__init__.mdx b/docs/python-sdk/fastmcp-apps.mdx similarity index 89% rename from docs/python-sdk/fastmcp-apps-__init__.mdx rename to docs/python-sdk/fastmcp-apps.mdx index 5f69a4b59..58bd24656 100644 --- a/docs/python-sdk/fastmcp-apps-__init__.mdx +++ b/docs/python-sdk/fastmcp-apps.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: apps +sidebarTitle: apps --- # `fastmcp.apps` diff --git a/docs/python-sdk/fastmcp-cli-apps_dev.mdx b/docs/python-sdk/fastmcp-cli-apps_dev.mdx deleted file mode 100644 index 2cbe0fd3e..000000000 --- a/docs/python-sdk/fastmcp-cli-apps_dev.mdx +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: apps_dev -sidebarTitle: apps_dev ---- - -# `fastmcp.cli.apps_dev` - - -Dev server for previewing FastMCPApp UIs locally. - -Starts the user's MCP server on a configurable port, then starts a lightweight -Starlette dev server that: - - - Serves a Prefab-based tool picker at GET / - - Proxies /mcp to the user's server (avoids browser CORS restrictions) - - Serves the AppBridge host page at GET /launch - -The host page uses @modelcontextprotocol/ext-apps to connect to the MCP server -and render the selected UI tool inside an iframe. - -Startup sequence ----------------- -1. Download ext-apps app-bridge.js from npm and patch its bare - ``@modelcontextprotocol/sdk/…`` imports to use concrete esm.sh URLs. -2. Detect the exact Zod v4 module URL that esm.sh serves for that SDK version - and build an import-map entry that redirects the broken ``v4.mjs`` (which - only re-exports ``{z, default}``) to ``v4/classic/index.mjs`` (which - correctly exports every named Zod v4 function). Import maps apply to the - full module graph in the document, including cross-origin esm.sh modules. -3. Serve both the patched JS and the import-map JSON from the dev server. - - -## Functions - -### `run_dev_apps` - -```python -run_dev_apps(server_spec: str) -> None -``` - - -Start the full dev environment for a FastMCPApp server. - -Starts the user's MCP server on *mcp_port*, starts the Prefab dev UI -on *dev_port* (with an /mcp proxy to the user's server), then opens -the browser. - diff --git a/docs/python-sdk/fastmcp-cli-auth.mdx b/docs/python-sdk/fastmcp-cli-auth.mdx deleted file mode 100644 index 586a53505..000000000 --- a/docs/python-sdk/fastmcp-cli-auth.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: auth -sidebarTitle: auth ---- - -# `fastmcp.cli.auth` - - -Authentication-related CLI commands. diff --git a/docs/python-sdk/fastmcp-cli-cimd.mdx b/docs/python-sdk/fastmcp-cli-cimd.mdx deleted file mode 100644 index 2b4b73457..000000000 --- a/docs/python-sdk/fastmcp-cli-cimd.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: cimd -sidebarTitle: cimd ---- - -# `fastmcp.cli.cimd` - - -CIMD (Client ID Metadata Document) CLI commands. - -## Functions - -### `create_command` - -```python -create_command() -> None -``` - - -Generate a CIMD document for hosting. - -Create a Client ID Metadata Document that you can host at an HTTPS URL. -The URL where you host this document becomes your client_id. - -After creating the document, host it at an HTTPS URL with a non-root path, -for example: https://myapp.example.com/oauth/client.json - - -### `validate_command` - -```python -validate_command(url: Annotated[str, cyclopts.Parameter(help='URL of the CIMD document to validate')]) -> None -``` - - -Validate a hosted CIMD document. - -Fetches the document from the given URL and validates: -- URL is valid CIMD URL (HTTPS, non-root path) -- Document is valid JSON -- Document conforms to CIMD schema -- client_id in document matches the URL - diff --git a/docs/python-sdk/fastmcp-cli-cli.mdx b/docs/python-sdk/fastmcp-cli-cli.mdx deleted file mode 100644 index d396af571..000000000 --- a/docs/python-sdk/fastmcp-cli-cli.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: cli -sidebarTitle: cli ---- - -# `fastmcp.cli.cli` - - -FastMCP CLI tools using Cyclopts. - -## Functions - -### `with_argv` - -```python -with_argv(args: list[str] | None) -``` - - -Temporarily replace sys.argv if args provided. - -This context manager is used at the CLI boundary to inject -server arguments when needed, without mutating sys.argv deep -in the source loading logic. - -Args are provided without the script name, so we preserve sys.argv[0] -and replace the rest. - - -### `version` - -```python -version() -``` - - -Display version information and platform details. - - -### `inspector` - -```python -inspector(server_spec: str | None = None) -> None -``` - - -Run an MCP server with the MCP Inspector for development. - -**Args:** -- `server_spec`: Python file to run, optionally with \:object suffix, or None to auto-detect fastmcp.json - - -### `apps` - -```python -apps(server_spec: str) -> None -``` - - -Preview a FastMCPApp UI in the browser. - -Starts the MCP server from SERVER_SPEC on --mcp-port, launches a local -dev UI on --dev-port with a tool picker and AppBridge host, then opens -the browser automatically. - -Requires fastmcp[apps] to be installed (prefab-ui). - - -### `run` - -```python -run(server_spec: str | None = None, *server_args: str) -> None -``` - - -Run an MCP server or connect to a remote one. - -The server can be specified in several ways: -1. Module approach: "server.py" - runs the module directly, looking for an object named 'mcp', 'server', or 'app' -2. Import approach: "server.py:app" - imports and runs the specified server object -3. URL approach: "http://server-url" - connects to a remote server and creates a proxy -4. MCPConfig file: "mcp.json" - runs as a proxy server for the MCP Servers in the MCPConfig file -5. FastMCP config: "fastmcp.json" - runs server using FastMCP configuration -6. No argument: looks for fastmcp.json in current directory -7. Module mode: "-m my_module" - runs the module directly via python -m - -Server arguments can be passed after -- : -fastmcp run server.py -- --config config.json --debug - -**Args:** -- `server_spec`: Python file, object specification (file\:obj), config file, URL, or None to auto-detect - - -### `inspect` - -```python -inspect(server_spec: str | None = None) -> None -``` - - -Inspect an MCP server and display information or generate a JSON report. - -This command analyzes an MCP server. Without flags, it displays a text summary. -Use --format to output complete JSON data. - -**Examples:** - -# Show text summary -fastmcp inspect server.py - -# Output FastMCP format JSON to stdout -fastmcp inspect server.py --format fastmcp - -# Save MCP protocol format to file (format required with -o) -fastmcp inspect server.py --format mcp -o manifest.json - -# Inspect from fastmcp.json configuration -fastmcp inspect fastmcp.json -fastmcp inspect # auto-detect fastmcp.json - -**Args:** -- `server_spec`: Python file to inspect, optionally with \:object suffix, or fastmcp.json - - -### `prepare` - -```python -prepare(config_path: Annotated[str | None, cyclopts.Parameter(help='Path to fastmcp.json configuration file')] = None, output_dir: Annotated[str | None, cyclopts.Parameter(help='Directory to create the persistent environment in')] = None, skip_source: Annotated[bool, cyclopts.Parameter(help='Skip source preparation (e.g., git clone)')] = False) -> None -``` - - -Prepare a FastMCP project by creating a persistent uv environment. - -This command creates a persistent uv project with all dependencies installed: -- Creates a pyproject.toml with dependencies from the config -- Installs all Python packages into a .venv -- Prepares the source (git clone, download, etc.) unless --skip-source - -After running this command, you can use: -fastmcp run <config> --project <output-dir> - -This is useful for: -- CI/CD pipelines with separate build and run stages -- Docker images where you prepare during build -- Production deployments where you want fast startup times - diff --git a/docs/python-sdk/fastmcp-cli-client.mdx b/docs/python-sdk/fastmcp-cli-client.mdx deleted file mode 100644 index 78dad8b29..000000000 --- a/docs/python-sdk/fastmcp-cli-client.mdx +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: client -sidebarTitle: client ---- - -# `fastmcp.cli.client` - - -Client-side CLI commands for querying and invoking MCP servers. - -## Functions - -### `resolve_server_spec` - -```python -resolve_server_spec(server_spec: str | None) -> str | dict[str, Any] | ClientTransport -``` - - -Turn CLI inputs into something ``Client()`` accepts. - -Exactly one of ``server_spec`` or ``command`` should be provided. - -Resolution order for ``server_spec``: -1. URLs (``http://``, ``https://``) — passed through as-is. - If ``--transport`` is ``sse``, the URL is rewritten to end with ``/sse`` - so ``infer_transport`` picks the right transport. -2. Existing file paths, or strings ending in ``.py``/``.js``/``.json``. -3. Anything else — name-based resolution via ``resolve_name``. - -When ``command`` is provided, the string is shell-split into a -``StdioTransport(command, args)``. - - -### `coerce_value` - -```python -coerce_value(raw: str, schema: dict[str, Any]) -> Any -``` - - -Coerce a string CLI value according to a JSON-Schema type hint. - - -### `parse_tool_arguments` - -```python -parse_tool_arguments(raw_args: tuple[str, ...], input_json: str | None, input_schema: dict[str, Any]) -> dict[str, Any] -``` - - -Build a tool-call argument dict from CLI inputs. - -A single JSON object argument is treated as the full argument dict. -``--input-json`` provides the base dict; ``key=value`` pairs override. -Values are coerced using the tool's ``inputSchema``. - - -### `format_tool_signature` - -```python -format_tool_signature(tool: mcp.types.Tool) -> str -``` - - -Build ``name(param: type, ...) -> return_type`` from a tool's JSON schemas. - - -### `list_command` - -```python -list_command(server_spec: Annotated[str | None, cyclopts.Parameter(help='Server URL, Python file, MCPConfig JSON, or .js file')] = None) -> None -``` - - -List tools available on an MCP server. - -**Examples:** - -fastmcp list http://localhost:8000/mcp -fastmcp list server.py -fastmcp list mcp.json --json -fastmcp list --command 'npx -y @mcp/server' --resources -fastmcp list http://server/mcp --transport sse - - -### `call_command` - -```python -call_command(server_spec: Annotated[str | None, cyclopts.Parameter(help='Server URL, Python file, MCPConfig JSON, or .js file')] = None, target: Annotated[str, cyclopts.Parameter(help='Tool name, resource URI, or prompt name (with --prompt)')] = '', *arguments: str) -> None -``` - - -Call a tool, read a resource, or get a prompt on an MCP server. - -By default the target is treated as a tool name. If the target -contains ``://`` it is treated as a resource URI. Pass ``--prompt`` -to treat it as a prompt name. - -Arguments are passed as key=value pairs. Use --input-json for complex -or nested arguments. - -**Examples:** - -``` -fastmcp call server.py greet name=World -fastmcp call server.py resource://docs/readme -fastmcp call server.py analyze --prompt data='[1,2,3]' -fastmcp call http://server/mcp create --input-json '{"tags": ["a","b"]}' -``` - - -### `discover_command` - -```python -discover_command() -> None -``` - - -Discover MCP servers configured in editor and project configs. - -Scans Claude Desktop, Claude Code, Cursor, Gemini CLI, Goose, and -project-level mcp.json files for MCP server definitions. - -Discovered server names can be used directly with ``fastmcp list`` -and ``fastmcp call`` instead of specifying a URL or file path. - -**Examples:** - -fastmcp discover -fastmcp discover --source claude-code -fastmcp discover --source cursor --source gemini --json -fastmcp list weather -fastmcp call cursor:weather get_forecast city=London - diff --git a/docs/python-sdk/fastmcp-cli-discovery.mdx b/docs/python-sdk/fastmcp-cli-discovery.mdx deleted file mode 100644 index 5892df9af..000000000 --- a/docs/python-sdk/fastmcp-cli-discovery.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: discovery -sidebarTitle: discovery ---- - -# `fastmcp.cli.discovery` - - -Discover MCP servers configured in editor config files. - -Scans filesystem-readable config files from editors like Claude Desktop, -Claude Code, Cursor, Gemini CLI, and Goose, as well as project-level -``mcp.json`` files. Each discovered server can be resolved by name -(or ``source:name``) so the CLI can connect without requiring a URL -or file path. - - -## Functions - -### `discover_servers` - -```python -discover_servers(start_dir: Path | None = None) -> list[DiscoveredServer] -``` - - -Run all scanners and return the combined results. - -Duplicate names across sources are preserved — callers can -use :pyattr:`DiscoveredServer.qualified_name` to disambiguate. - - -### `resolve_name` - -```python -resolve_name(name: str, start_dir: Path | None = None) -> ClientTransport -``` - - -Resolve a server name (or ``source:name``) to a transport. - -Raises :class:`ValueError` when the name is not found or is ambiguous. - - -## Classes - -### `DiscoveredServer` - - -A single MCP server found in an editor or project config. - - -**Methods:** - -#### `qualified_name` - -```python -qualified_name(self) -> str -``` - -Fully qualified ``source:name`` identifier. - - -#### `transport_summary` - -```python -transport_summary(self) -> str -``` - -Human-readable one-liner describing the transport. - diff --git a/docs/python-sdk/fastmcp-cli-generate.mdx b/docs/python-sdk/fastmcp-cli-generate.mdx deleted file mode 100644 index 0d9285189..000000000 --- a/docs/python-sdk/fastmcp-cli-generate.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: generate -sidebarTitle: generate ---- - -# `fastmcp.cli.generate` - - -Generate a standalone CLI script and agent skill from an MCP server. - -## Functions - -### `serialize_transport` - -```python -serialize_transport(resolved: str | dict[str, Any] | ClientTransport) -> tuple[str, set[str]] -``` - - -Serialize a resolved transport to a Python expression string. - -Returns ``(expression, extra_imports)`` where *extra_imports* is a set of -import lines needed by the expression. - - -### `generate_cli_script` - -```python -generate_cli_script(server_name: str, server_spec: str, transport_code: str, extra_imports: set[str], tools: list[mcp.types.Tool]) -> str -``` - - -Generate the full CLI script source code. - - -### `generate_skill_content` - -```python -generate_skill_content(server_name: str, cli_filename: str, tools: list[mcp.types.Tool]) -> str -``` - - -Generate a SKILL.md file for a generated CLI script. - - -### `generate_cli_command` - -```python -generate_cli_command(server_spec: Annotated[str, cyclopts.Parameter(help='Server URL, Python file, MCPConfig JSON, discovered name, or .js file')], output: Annotated[str, cyclopts.Parameter(help='Output file path (default: cli.py)')] = 'cli.py') -> None -``` - - -Generate a standalone CLI script from an MCP server. - -Connects to the server, reads its tools/resources/prompts, and writes -a Python script that can invoke them directly. Also generates a SKILL.md -agent skill file unless --no-skill is passed. - -**Examples:** - -fastmcp generate-cli weather -fastmcp generate-cli weather my_cli.py -fastmcp generate-cli http://localhost:8000/mcp -fastmcp generate-cli server.py output.py -f -fastmcp generate-cli weather --no-skill - diff --git a/docs/python-sdk/fastmcp-cli-install-__init__.mdx b/docs/python-sdk/fastmcp-cli-install-__init__.mdx deleted file mode 100644 index 3909565f2..000000000 --- a/docs/python-sdk/fastmcp-cli-install-__init__.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.cli.install` - - -Install subcommands for FastMCP CLI using Cyclopts. diff --git a/docs/python-sdk/fastmcp-cli-install-claude_code.mdx b/docs/python-sdk/fastmcp-cli-install-claude_code.mdx deleted file mode 100644 index 675faafc4..000000000 --- a/docs/python-sdk/fastmcp-cli-install-claude_code.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: claude_code -sidebarTitle: claude_code ---- - -# `fastmcp.cli.install.claude_code` - - -Claude Code integration for FastMCP install using Cyclopts. - -## Functions - -### `find_claude_command` - -```python -find_claude_command() -> str | None -``` - - -Find the Claude Code CLI command. - -Checks common installation locations since 'claude' is often a shell alias -that doesn't work with subprocess calls. - - -### `check_claude_code_available` - -```python -check_claude_code_available() -> bool -``` - - -Check if Claude Code CLI is available. - - -### `install_claude_code` - -```python -install_claude_code(file: Path, server_object: str | None, name: str) -> bool -``` - - -Install FastMCP server in Claude Code. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `name`: Name for the server in Claude Code -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `env_vars`: Optional dictionary of environment variables -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within - -**Returns:** -- True if installation was successful, False otherwise - - -### `claude_code_command` - -```python -claude_code_command(server_spec: str) -> None -``` - - -Install an MCP server in Claude Code. - -**Args:** -- `server_spec`: Python file to install, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-install-claude_desktop.mdx b/docs/python-sdk/fastmcp-cli-install-claude_desktop.mdx deleted file mode 100644 index 2c06c6020..000000000 --- a/docs/python-sdk/fastmcp-cli-install-claude_desktop.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: claude_desktop -sidebarTitle: claude_desktop ---- - -# `fastmcp.cli.install.claude_desktop` - - -Claude Desktop integration for FastMCP install using Cyclopts. - -## Functions - -### `get_claude_config_path` - -```python -get_claude_config_path(config_path: Path | None = None) -> Path | None -``` - - -Get the Claude config directory based on platform. - -**Args:** -- `config_path`: Optional custom path to the Claude Desktop config directory - - -### `install_claude_desktop` - -```python -install_claude_desktop(file: Path, server_object: str | None, name: str) -> bool -``` - - -Install FastMCP server in Claude Desktop. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `name`: Name for the server in Claude's config -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `env_vars`: Optional dictionary of environment variables -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within -- `config_path`: Optional custom path to Claude Desktop config directory - -**Returns:** -- True if installation was successful, False otherwise - - -### `claude_desktop_command` - -```python -claude_desktop_command(server_spec: str) -> None -``` - - -Install an MCP server in Claude Desktop. - -**Args:** -- `server_spec`: Python file to install, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-install-cursor.mdx b/docs/python-sdk/fastmcp-cli-install-cursor.mdx deleted file mode 100644 index e6a964eed..000000000 --- a/docs/python-sdk/fastmcp-cli-install-cursor.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: cursor -sidebarTitle: cursor ---- - -# `fastmcp.cli.install.cursor` - - -Cursor integration for FastMCP install using Cyclopts. - -## Functions - -### `generate_cursor_deeplink` - -```python -generate_cursor_deeplink(server_name: str, server_config: StdioMCPServer) -> str -``` - - -Generate a Cursor deeplink for installing the MCP server. - -**Args:** -- `server_name`: Name of the server -- `server_config`: Server configuration - -**Returns:** -- Deeplink URL that can be clicked to install the server - - -### `open_deeplink` - -```python -open_deeplink(deeplink: str) -> bool -``` - - -Attempt to open a Cursor deeplink URL using the system's default handler. - -**Args:** -- `deeplink`: The deeplink URL to open - -**Returns:** -- True if the command succeeded, False otherwise - - -### `install_cursor_workspace` - -```python -install_cursor_workspace(file: Path, server_object: str | None, name: str, workspace_path: Path) -> bool -``` - - -Install FastMCP server to workspace-specific Cursor configuration. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `name`: Name for the server in Cursor -- `workspace_path`: Path to the workspace directory -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `env_vars`: Optional dictionary of environment variables -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within - -**Returns:** -- True if installation was successful, False otherwise - - -### `install_cursor` - -```python -install_cursor(file: Path, server_object: str | None, name: str) -> bool -``` - - -Install FastMCP server in Cursor. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `name`: Name for the server in Cursor -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `env_vars`: Optional dictionary of environment variables -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within -- `workspace`: Optional workspace directory for project-specific installation - -**Returns:** -- True if installation was successful, False otherwise - - -### `cursor_command` - -```python -cursor_command(server_spec: str) -> None -``` - - -Install an MCP server in Cursor. - -**Args:** -- `server_spec`: Python file to install, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-install-gemini_cli.mdx b/docs/python-sdk/fastmcp-cli-install-gemini_cli.mdx deleted file mode 100644 index d80716460..000000000 --- a/docs/python-sdk/fastmcp-cli-install-gemini_cli.mdx +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: gemini_cli -sidebarTitle: gemini_cli ---- - -# `fastmcp.cli.install.gemini_cli` - - -Gemini CLI integration for FastMCP install using Cyclopts. - -## Functions - -### `find_gemini_command` - -```python -find_gemini_command() -> str | None -``` - - -Find the Gemini CLI command. - - -### `check_gemini_cli_available` - -```python -check_gemini_cli_available() -> bool -``` - - -Check if Gemini CLI is available. - - -### `install_gemini_cli` - -```python -install_gemini_cli(file: Path, server_object: str | None, name: str) -> bool -``` - - -Install FastMCP server in Gemini CLI. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `name`: Name for the server in Gemini CLI -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `env_vars`: Optional dictionary of environment variables -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within - -**Returns:** -- True if installation was successful, False otherwise - - -### `gemini_cli_command` - -```python -gemini_cli_command(server_spec: str) -> None -``` - - -Install an MCP server in Gemini CLI. - -**Args:** -- `server_spec`: Python file to install, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-install-goose.mdx b/docs/python-sdk/fastmcp-cli-install-goose.mdx deleted file mode 100644 index af5aed24c..000000000 --- a/docs/python-sdk/fastmcp-cli-install-goose.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: goose -sidebarTitle: goose ---- - -# `fastmcp.cli.install.goose` - - -Goose integration for FastMCP install using Cyclopts. - -## Functions - -### `generate_goose_deeplink` - -```python -generate_goose_deeplink(name: str, command: str, args: list[str]) -> str -``` - - -Generate a Goose deeplink for installing an MCP extension. - -**Args:** -- `name`: Human-readable display name for the extension. -- `command`: The executable command (e.g. "uv"). -- `args`: Arguments to the command. -- `description`: Short description shown in Goose. - -**Returns:** -- A goose://extension?... deeplink URL. - - -### `install_goose` - -```python -install_goose(file: Path, server_object: str | None, name: str) -> bool -``` - - -Install FastMCP server in Goose via deeplink. - -**Args:** -- `file`: Path to the server file. -- `server_object`: Optional server object name (for \:object suffix). -- `name`: Name for the extension in Goose. -- `with_packages`: Optional list of additional packages to install. -- `python_version`: Optional Python version to use. - -**Returns:** -- True if installation was successful, False otherwise. - - -### `goose_command` - -```python -goose_command(server_spec: str) -> None -``` - - -Install an MCP server in Goose. - -Uses uvx to run the server. Environment variables are not included -in the deeplink; use `fastmcp install mcp-json` to generate a full -config for manual installation. - -**Args:** -- `server_spec`: Python file to install, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-install-mcp_json.mdx b/docs/python-sdk/fastmcp-cli-install-mcp_json.mdx deleted file mode 100644 index a9eca1e51..000000000 --- a/docs/python-sdk/fastmcp-cli-install-mcp_json.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: mcp_json -sidebarTitle: mcp_json ---- - -# `fastmcp.cli.install.mcp_json` - - -MCP configuration JSON generation for FastMCP install using Cyclopts. - -## Functions - -### `install_mcp_json` - -```python -install_mcp_json(file: Path, server_object: str | None, name: str) -> bool -``` - - -Generate MCP configuration JSON for manual installation. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `name`: Name for the server in MCP config -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `env_vars`: Optional dictionary of environment variables -- `copy`: If True, copy to clipboard instead of printing to stdout -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within - -**Returns:** -- True if generation was successful, False otherwise - - -### `mcp_json_command` - -```python -mcp_json_command(server_spec: str) -> None -``` - - -Generate MCP configuration JSON for manual installation. - -**Args:** -- `server_spec`: Python file to install, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-install-shared.mdx b/docs/python-sdk/fastmcp-cli-install-shared.mdx deleted file mode 100644 index b51b0a424..000000000 --- a/docs/python-sdk/fastmcp-cli-install-shared.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: shared -sidebarTitle: shared ---- - -# `fastmcp.cli.install.shared` - - -Shared utilities for install commands. - -## Functions - -### `validate_server_name` - -```python -validate_server_name(name: str) -> str -``` - - -Validate that a server name is safe for use as a subprocess argument. - -Raises SystemExit if the name contains shell metacharacters. - - -### `parse_env_var` - -```python -parse_env_var(env_var: str) -> tuple[str, str] -``` - - -Parse environment variable string in format KEY=VALUE. - - -### `process_common_args` - -```python -process_common_args(server_spec: str, server_name: str | None, with_packages: list[str] | None, env_vars: list[str] | None, env_file: Path | None) -> tuple[Path, str | None, str, list[str], dict[str, str] | None] -``` - - -Process common arguments shared by all install commands. - -Handles both fastmcp.json config files and traditional file.py:object syntax. - - -### `open_deeplink` - -```python -open_deeplink(url: str) -> bool -``` - - -Attempt to open a deeplink URL using the system's default handler. - -**Args:** -- `url`: The deeplink URL to open. -- `expected_scheme`: The URL scheme to validate (e.g. "cursor", "goose"). - -**Returns:** -- True if the command succeeded, False otherwise. - diff --git a/docs/python-sdk/fastmcp-cli-install-stdio.mdx b/docs/python-sdk/fastmcp-cli-install-stdio.mdx deleted file mode 100644 index 62bdc8fde..000000000 --- a/docs/python-sdk/fastmcp-cli-install-stdio.mdx +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: stdio -sidebarTitle: stdio ---- - -# `fastmcp.cli.install.stdio` - - -Stdio command generation for FastMCP install using Cyclopts. - -## Functions - -### `install_stdio` - -```python -install_stdio(file: Path, server_object: str | None) -> bool -``` - - -Generate the stdio command for running a FastMCP server. - -**Args:** -- `file`: Path to the server file -- `server_object`: Optional server object name (for \:object suffix) -- `with_editable`: Optional list of directories to install in editable mode -- `with_packages`: Optional list of additional packages to install -- `copy`: If True, copy to clipboard instead of printing to stdout -- `python_version`: Optional Python version to use -- `with_requirements`: Optional requirements file to install from -- `project`: Optional project directory to run within - -**Returns:** -- True if generation was successful, False otherwise - - -### `stdio_command` - -```python -stdio_command(server_spec: str) -> None -``` - - -Generate the stdio command for running a FastMCP server. - -Outputs the shell command that an MCP host would use to start this server -over stdio transport. Useful for manual configuration or debugging. - -**Args:** -- `server_spec`: Python file to run, optionally with \:object suffix - diff --git a/docs/python-sdk/fastmcp-cli-run.mdx b/docs/python-sdk/fastmcp-cli-run.mdx deleted file mode 100644 index 1b7af37a5..000000000 --- a/docs/python-sdk/fastmcp-cli-run.mdx +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: run -sidebarTitle: run ---- - -# `fastmcp.cli.run` - - -FastMCP run command implementation with enhanced type hints. - -## Functions - -### `is_url` - -```python -is_url(path: str) -> bool -``` - - -Check if a string is a URL. - - -### `create_client_server` - -```python -create_client_server(url: str) -> Any -``` - - -Create a FastMCP server from a client URL. - -**Args:** -- `url`: The URL to connect to - -**Returns:** -- A FastMCP server instance - - -### `create_mcp_config_server` - -```python -create_mcp_config_server(mcp_config_path: Path) -> FastMCP[None] -``` - - -Create a FastMCP server from a MCPConfig. - - -### `load_mcp_server_config` - -```python -load_mcp_server_config(config_path: Path) -> MCPServerConfig -``` - - -Load a FastMCP configuration from a fastmcp.json file. - -**Args:** -- `config_path`: Path to fastmcp.json file - -**Returns:** -- MCPServerConfig object - - -### `run_command` - -```python -run_command(server_spec: str, transport: TransportType | None = None, host: str | None = None, port: int | None = None, path: str | None = None, log_level: LogLevelType | None = None, server_args: list[str] | None = None, show_banner: bool = True, use_direct_import: bool = False, skip_source: bool = False, stateless: bool = False) -> None -``` - - -Run a MCP server or connect to a remote one. - -**Args:** -- `server_spec`: Python file, object specification (file\:obj), config file, or URL -- `transport`: Transport protocol to use -- `host`: Host to bind to when using http transport -- `port`: Port to bind to when using http transport -- `path`: Path to bind to when using http transport -- `log_level`: Log level -- `server_args`: Additional arguments to pass to the server -- `show_banner`: Whether to show the server banner -- `use_direct_import`: Whether to use direct import instead of subprocess -- `skip_source`: Whether to skip source preparation step -- `stateless`: Whether to run in stateless mode (no session) - - -### `run_module_command` - -```python -run_module_command(module_name: str) -> None -``` - - -Run a Python module directly using ``python -m ``. - -When ``-m`` is used, the module manages its own server startup. -No server-object discovery or transport overrides are applied. - -**Args:** -- `module_name`: Dotted module name (e.g. ``my_package``). -- `env_command_builder`: An optional callable that wraps a command list -with environment setup (e.g. ``UVEnvironment.build_command``). -- `extra_args`: Extra arguments forwarded after the module name. - - -### `run_v1_server_async` - -```python -run_v1_server_async(server: FastMCP1x, host: str | None = None, port: int | None = None, transport: TransportType | None = None) -> None -``` - - -Run a FastMCP 1.x server using async methods. - -**Args:** -- `server`: FastMCP 1.x server instance -- `host`: Host to bind to -- `port`: Port to bind to -- `transport`: Transport protocol to use - - -### `run_with_reload` - -```python -run_with_reload(cmd: list[str], reload_dirs: list[Path] | None = None, is_stdio: bool = False) -> None -``` - - -Run a command with file watching and auto-reload. - -**Args:** -- `cmd`: Command to run as subprocess (should include --no-reload) -- `reload_dirs`: Directories to watch for changes (default\: cwd) -- `is_stdio`: Whether this is stdio transport - diff --git a/docs/python-sdk/fastmcp-cli-tasks.mdx b/docs/python-sdk/fastmcp-cli-tasks.mdx deleted file mode 100644 index 99f5dac1f..000000000 --- a/docs/python-sdk/fastmcp-cli-tasks.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: tasks -sidebarTitle: tasks ---- - -# `fastmcp.cli.tasks` - - -FastMCP tasks CLI for Docket task management. - -## Functions - -### `check_distributed_backend` - -```python -check_distributed_backend() -> None -``` - - -Check if Docket is configured with a distributed backend. - -The CLI worker runs as a separate process, so it needs Redis/Valkey -to coordinate with the main server process. - -**Raises:** -- `SystemExit`: If using memory\:// URL - - -### `worker` - -```python -worker(server_spec: Annotated[str | None, cyclopts.Parameter(help='Python file to run, optionally with :object suffix, or None to auto-detect fastmcp.json')] = None) -> None -``` - - -Start an additional worker to process background tasks. - -Connects to your Docket backend and processes tasks in parallel with -any other running workers. Configure via environment variables -(FASTMCP_DOCKET_*). - diff --git a/docs/python-sdk/fastmcp-cli-__init__.mdx b/docs/python-sdk/fastmcp-cli.mdx similarity index 55% rename from docs/python-sdk/fastmcp-cli-__init__.mdx rename to docs/python-sdk/fastmcp-cli.mdx index d2873740a..4cc13272a 100644 --- a/docs/python-sdk/fastmcp-cli-__init__.mdx +++ b/docs/python-sdk/fastmcp-cli.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: cli +sidebarTitle: cli --- # `fastmcp.cli` diff --git a/docs/python-sdk/fastmcp-client-auth-__init__.mdx b/docs/python-sdk/fastmcp-client-auth-__init__.mdx deleted file mode 100644 index 28242780d..000000000 --- a/docs/python-sdk/fastmcp-client-auth-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.client.auth` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-client-auth-bearer.mdx b/docs/python-sdk/fastmcp-client-auth-bearer.mdx deleted file mode 100644 index a6a53a3a6..000000000 --- a/docs/python-sdk/fastmcp-client-auth-bearer.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: bearer -sidebarTitle: bearer ---- - -# `fastmcp.client.auth.bearer` - -## Classes - -### `BearerAuth` - -**Methods:** - -#### `auth_flow` - -```python -auth_flow(self, request) -``` diff --git a/docs/python-sdk/fastmcp-client-auth-oauth.mdx b/docs/python-sdk/fastmcp-client-auth-oauth.mdx deleted file mode 100644 index 85d4e536a..000000000 --- a/docs/python-sdk/fastmcp-client-auth-oauth.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: oauth -sidebarTitle: oauth ---- - -# `fastmcp.client.auth.oauth` - -## Functions - -### `check_if_auth_required` - -```python -check_if_auth_required(mcp_url: str, httpx_kwargs: dict[str, Any] | None = None) -> bool -``` - - -Check if the MCP endpoint requires authentication by making a test request. - -**Returns:** -- True if auth appears to be required, False otherwise - - -## Classes - -### `ClientNotFoundError` - - -Raised when OAuth client credentials are not found on the server. - - -### `TokenStorageAdapter` - -**Methods:** - -#### `clear` - -```python -clear(self) -> None -``` - -#### `get_tokens` - -```python -get_tokens(self) -> OAuthToken | None -``` - -#### `set_tokens` - -```python -set_tokens(self, tokens: OAuthToken) -> None -``` - -#### `get_token_expiry` - -```python -get_token_expiry(self) -> float | None -``` - -#### `get_client_info` - -```python -get_client_info(self) -> OAuthClientInformationFull | None -``` - -#### `set_client_info` - -```python -set_client_info(self, client_info: OAuthClientInformationFull) -> None -``` - -### `OAuth` - - -OAuth client provider for MCP servers with browser-based authentication. - -This class provides OAuth authentication for FastMCP clients by opening -a browser for user authorization and running a local callback server. - - -**Methods:** - -#### `redirect_handler` - -```python -redirect_handler(self, authorization_url: str) -> None -``` - -Open browser for authorization, with pre-flight check for invalid client. - - -#### `callback_handler` - -```python -callback_handler(self) -> tuple[str, str | None] -``` - -Handle OAuth callback and return (auth_code, state). - - -#### `async_auth_flow` - -```python -async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response] -``` - -HTTPX auth flow with automatic retry on stale cached credentials. - -If the OAuth flow fails due to invalid/stale client credentials, -clears the cache and retries once with fresh registration. - diff --git a/docs/python-sdk/fastmcp-client-client.mdx b/docs/python-sdk/fastmcp-client-client.mdx deleted file mode 100644 index 45158d509..000000000 --- a/docs/python-sdk/fastmcp-client-client.mdx +++ /dev/null @@ -1,286 +0,0 @@ ---- -title: client -sidebarTitle: client ---- - -# `fastmcp.client.client` - -## Classes - -### `ClientSessionState` - - -Holds all session-related state for a Client instance. - -This allows clean separation of configuration (which is copied) from -session state (which should be fresh for each new client instance). - - -### `CallToolResult` - - -Parsed result from a tool call. - - -### `Client` - - -MCP client that delegates connection management to a Transport instance. - -The Client class is responsible for MCP protocol logic, while the Transport -handles connection establishment and management. Client provides methods for -working with resources, prompts, tools and other MCP capabilities. - -This client supports reentrant context managers (multiple concurrent -`async with client:` blocks) using reference counting and background session -management. This allows efficient session reuse in any scenario with -nested or concurrent client usage. - -MCP SDK 1.10 introduced automatic list_tools() calls during call_tool() -execution. This created a race condition where events could be reset while -other tasks were waiting on them, causing deadlocks. The issue was exposed -in proxy scenarios but affects any reentrant usage. - -The solution uses reference counting to track active context managers, -a background task to manage the session lifecycle, events to coordinate -between tasks, and ensures all session state changes happen within a lock. -Events are only created when needed, never reset outside locks. - -This design prevents race conditions where tasks wait on events that get -replaced by other tasks, ensuring reliable coordination in concurrent scenarios. - -**Args:** -- `transport`: -Connection source specification, which can be\: - - - ClientTransport\: Direct transport instance - - FastMCP\: In-process FastMCP server - - AnyUrl or str\: URL to connect to - - Path\: File path for local socket - - MCPConfig\: MCP server configuration - - dict\: Transport configuration -- `roots`: Optional RootsList or RootsHandler for filesystem access -- `sampling_handler`: Optional handler for sampling requests -- `log_handler`: Optional handler for log messages -- `message_handler`: Optional handler for protocol messages -- `progress_handler`: Optional handler for progress notifications -- `timeout`: Optional timeout for requests (seconds or timedelta) -- `init_timeout`: Optional timeout for initial connection (seconds or timedelta). -Set to 0 to disable. If None, uses the value in the FastMCP global settings. - -**Examples:** - -```python -# Connect to FastMCP server -client = Client("http://localhost:8080") - -async with client: - # List available resources - resources = await client.list_resources() - - # Call a tool - result = await client.call_tool("my_tool", {"param": "value"}) -``` - - -**Methods:** - -#### `session` - -```python -session(self) -> ClientSession -``` - -Get the current active session. Raises RuntimeError if not connected. - - -#### `initialize_result` - -```python -initialize_result(self) -> mcp.types.InitializeResult | None -``` - -Get the result of the initialization request. - - -#### `set_roots` - -```python -set_roots(self, roots: RootsList | RootsHandler) -> None -``` - -Set the roots for the client. This does not automatically call `send_roots_list_changed`. - - -#### `set_sampling_callback` - -```python -set_sampling_callback(self, sampling_callback: SamplingHandler, sampling_capabilities: mcp.types.SamplingCapability | None = None) -> None -``` - -Set the sampling callback for the client. - - -#### `set_elicitation_callback` - -```python -set_elicitation_callback(self, elicitation_callback: ElicitationHandler) -> None -``` - -Set the elicitation callback for the client. - - -#### `is_connected` - -```python -is_connected(self) -> bool -``` - -Check if the client is currently connected. - - -#### `new` - -```python -new(self) -> Client[ClientTransportT] -``` - -Create a new client instance with the same configuration but fresh session state. - -This creates a new client with the same transport, handlers, and configuration, -but with no active session. Useful for creating independent sessions that don't -share state with the original client. - -**Returns:** -- A new Client instance with the same configuration but disconnected state. - - -#### `initialize` - -```python -initialize(self, timeout: datetime.timedelta | float | int | None = None) -> mcp.types.InitializeResult -``` - -Send an initialize request to the server. - -This method performs the MCP initialization handshake with the server, -exchanging capabilities and server information. It is idempotent - calling -it multiple times returns the cached result from the first call. - -The initialization happens automatically when entering the client context -manager unless `auto_initialize=False` was set during client construction. -Manual calls to this method are only needed when auto-initialization is disabled. - -**Args:** -- `timeout`: Optional timeout for the initialization request (seconds or timedelta). -If None, uses the client's init_timeout setting. - -**Returns:** -- The server's initialization response containing server info, -capabilities, protocol version, and optional instructions. - -**Raises:** -- `RuntimeError`: If the client is not connected or initialization times out. - - -#### `close` - -```python -close(self) -``` - -#### `ping` - -```python -ping(self) -> bool -``` - -Send a ping request. - - -#### `cancel` - -```python -cancel(self, request_id: str | int, reason: str | None = None) -> None -``` - -Send a cancellation notification for an in-progress request. - - -#### `progress` - -```python -progress(self, progress_token: str | int, progress: float, total: float | None = None, message: str | None = None) -> None -``` - -Send a progress notification. - - -#### `set_logging_level` - -```python -set_logging_level(self, level: mcp.types.LoggingLevel) -> None -``` - -Send a logging/setLevel request. - - -#### `send_roots_list_changed` - -```python -send_roots_list_changed(self) -> None -``` - -Send a roots/list_changed notification. - - -#### `complete_mcp` - -```python -complete_mcp(self, ref: mcp.types.ResourceTemplateReference | mcp.types.PromptReference, argument: dict[str, str], context_arguments: dict[str, Any] | None = None) -> mcp.types.CompleteResult -``` - -Send a completion request and return the complete MCP protocol result. - -**Args:** -- `ref`: The reference to complete. -- `argument`: Arguments to pass to the completion request. -- `context_arguments`: Optional context arguments to -include with the completion request. Defaults to None. - -**Returns:** -- mcp.types.CompleteResult: The complete response object from the protocol, -containing the completion and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `complete` - -```python -complete(self, ref: mcp.types.ResourceTemplateReference | mcp.types.PromptReference, argument: dict[str, str], context_arguments: dict[str, Any] | None = None) -> mcp.types.Completion -``` - -Send a completion request to the server. - -**Args:** -- `ref`: The reference to complete. -- `argument`: Arguments to pass to the completion request. -- `context_arguments`: Optional context arguments to -include with the completion request. Defaults to None. - -**Returns:** -- mcp.types.Completion: The completion object. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `generate_name` - -```python -generate_name(cls, name: str | None = None) -> str -``` diff --git a/docs/python-sdk/fastmcp-client-elicitation.mdx b/docs/python-sdk/fastmcp-client-elicitation.mdx deleted file mode 100644 index c9db14702..000000000 --- a/docs/python-sdk/fastmcp-client-elicitation.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: elicitation -sidebarTitle: elicitation ---- - -# `fastmcp.client.elicitation` - -## Functions - -### `create_elicitation_callback` - -```python -create_elicitation_callback(elicitation_handler: ElicitationHandler) -> ElicitationFnT -``` - -## Classes - -### `ElicitResult` diff --git a/docs/python-sdk/fastmcp-client-logging.mdx b/docs/python-sdk/fastmcp-client-logging.mdx deleted file mode 100644 index b9453a0be..000000000 --- a/docs/python-sdk/fastmcp-client-logging.mdx +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: logging -sidebarTitle: logging ---- - -# `fastmcp.client.logging` - -## Functions - -### `default_log_handler` - -```python -default_log_handler(message: LogMessage) -> None -``` - - -Default handler that properly routes server log messages to appropriate log levels. - - -### `create_log_callback` - -```python -create_log_callback(handler: LogHandler | None = None) -> LoggingFnT -``` diff --git a/docs/python-sdk/fastmcp-client-messages.mdx b/docs/python-sdk/fastmcp-client-messages.mdx deleted file mode 100644 index fde8f0cde..000000000 --- a/docs/python-sdk/fastmcp-client-messages.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: messages -sidebarTitle: messages ---- - -# `fastmcp.client.messages` - -## Classes - -### `MessageHandler` - - -This class is used to handle MCP messages sent to the client. It is used to handle all messages, -requests, notifications, and exceptions. Users can override any of the hooks - - -**Methods:** - -#### `dispatch` - -```python -dispatch(self, message: Message) -> None -``` - -#### `on_message` - -```python -on_message(self, message: Message) -> None -``` - -#### `on_request` - -```python -on_request(self, message: RequestResponder[mcp.types.ServerRequest, mcp.types.ClientResult]) -> None -``` - -#### `on_ping` - -```python -on_ping(self, message: mcp.types.PingRequest) -> None -``` - -#### `on_list_roots` - -```python -on_list_roots(self, message: mcp.types.ListRootsRequest) -> None -``` - -#### `on_create_message` - -```python -on_create_message(self, message: mcp.types.CreateMessageRequest) -> None -``` - -#### `on_notification` - -```python -on_notification(self, message: mcp.types.ServerNotification) -> None -``` - -#### `on_exception` - -```python -on_exception(self, message: Exception) -> None -``` - -#### `on_progress` - -```python -on_progress(self, message: mcp.types.ProgressNotification) -> None -``` - -#### `on_logging_message` - -```python -on_logging_message(self, message: mcp.types.LoggingMessageNotification) -> None -``` - -#### `on_tool_list_changed` - -```python -on_tool_list_changed(self, message: mcp.types.ToolListChangedNotification) -> None -``` - -#### `on_resource_list_changed` - -```python -on_resource_list_changed(self, message: mcp.types.ResourceListChangedNotification) -> None -``` - -#### `on_prompt_list_changed` - -```python -on_prompt_list_changed(self, message: mcp.types.PromptListChangedNotification) -> None -``` - -#### `on_resource_updated` - -```python -on_resource_updated(self, message: mcp.types.ResourceUpdatedNotification) -> None -``` - -#### `on_cancelled` - -```python -on_cancelled(self, message: mcp.types.CancelledNotification) -> None -``` diff --git a/docs/python-sdk/fastmcp-client-mixins-__init__.mdx b/docs/python-sdk/fastmcp-client-mixins-__init__.mdx deleted file mode 100644 index bc0e32a4c..000000000 --- a/docs/python-sdk/fastmcp-client-mixins-__init__.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.client.mixins` - - -Client mixins for FastMCP. diff --git a/docs/python-sdk/fastmcp-client-mixins-prompts.mdx b/docs/python-sdk/fastmcp-client-mixins-prompts.mdx deleted file mode 100644 index 6a859f06a..000000000 --- a/docs/python-sdk/fastmcp-client-mixins-prompts.mdx +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: prompts -sidebarTitle: prompts ---- - -# `fastmcp.client.mixins.prompts` - - -Prompt-related methods for FastMCP Client. - -## Classes - -### `ClientPromptsMixin` - - -Mixin providing prompt-related methods for Client. - - -**Methods:** - -#### `list_prompts_mcp` - -```python -list_prompts_mcp(self: Client) -> mcp.types.ListPromptsResult -``` - -Send a prompts/list request and return the complete MCP protocol result. - -**Args:** -- `cursor`: Optional pagination cursor from a previous request's nextCursor. - -**Returns:** -- mcp.types.ListPromptsResult: The complete response object from the protocol, -containing the list of prompts and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `list_prompts` - -```python -list_prompts(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.Prompt] -``` - -Retrieve all prompts available on the server. - -This method automatically fetches all pages if the server paginates results, -returning the complete list. For manual pagination control (e.g., to handle -large result sets incrementally), use list_prompts_mcp() with the cursor parameter. - -**Args:** -- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250. - -**Returns:** -- list\[mcp.types.Prompt]: A list of all Prompt objects. - -**Raises:** -- `RuntimeError`: If the page limit is reached before pagination completes. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `get_prompt_mcp` - -```python -get_prompt_mcp(self: Client, name: str, arguments: dict[str, Any] | None = None, meta: dict[str, Any] | None = None) -> mcp.types.GetPromptResult -``` - -Send a prompts/get request and return the complete MCP protocol result. - -**Args:** -- `name`: The name of the prompt to retrieve. -- `arguments`: Arguments to pass to the prompt. Defaults to None. -- `meta`: Request metadata (e.g., for SEP-1686 tasks). Defaults to None. - -**Returns:** -- mcp.types.GetPromptResult: The complete response object from the protocol, -containing the prompt messages and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `get_prompt` - -```python -get_prompt(self: Client, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.GetPromptResult -``` - -#### `get_prompt` - -```python -get_prompt(self: Client, name: str, arguments: dict[str, Any] | None = None) -> PromptTask -``` - -#### `get_prompt` - -```python -get_prompt(self: Client, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.GetPromptResult | PromptTask -``` - -Retrieve a rendered prompt message list from the server. - -**Args:** -- `name`: The name of the prompt to retrieve. -- `arguments`: Arguments to pass to the prompt. Defaults to None. -- `version`: Specific prompt version to get. If None, gets highest version. -- `meta`: Optional request-level metadata. -- `task`: If True, execute as background task (SEP-1686). Defaults to False. -- `task_id`: Optional client-provided task ID (auto-generated if not provided). -- `ttl`: Time to keep results available in milliseconds (default 60s). - -**Returns:** -- mcp.types.GetPromptResult | PromptTask: The complete response object if task=False, -or a PromptTask object if task=True. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - diff --git a/docs/python-sdk/fastmcp-client-mixins-resources.mdx b/docs/python-sdk/fastmcp-client-mixins-resources.mdx deleted file mode 100644 index 0f1f81d88..000000000 --- a/docs/python-sdk/fastmcp-client-mixins-resources.mdx +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: resources -sidebarTitle: resources ---- - -# `fastmcp.client.mixins.resources` - - -Resource-related methods for FastMCP Client. - -## Classes - -### `ClientResourcesMixin` - - -Mixin providing resource-related methods for Client. - - -**Methods:** - -#### `list_resources_mcp` - -```python -list_resources_mcp(self: Client) -> mcp.types.ListResourcesResult -``` - -Send a resources/list request and return the complete MCP protocol result. - -**Args:** -- `cursor`: Optional pagination cursor from a previous request's nextCursor. - -**Returns:** -- mcp.types.ListResourcesResult: The complete response object from the protocol, -containing the list of resources and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `list_resources` - -```python -list_resources(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.Resource] -``` - -Retrieve all resources available on the server. - -This method automatically fetches all pages if the server paginates results, -returning the complete list. For manual pagination control (e.g., to handle -large result sets incrementally), use list_resources_mcp() with the cursor parameter. - -**Args:** -- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250. - -**Returns:** -- list\[mcp.types.Resource]: A list of all Resource objects. - -**Raises:** -- `RuntimeError`: If the page limit is reached before pagination completes. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `list_resource_templates_mcp` - -```python -list_resource_templates_mcp(self: Client) -> mcp.types.ListResourceTemplatesResult -``` - -Send a resources/listResourceTemplates request and return the complete MCP protocol result. - -**Args:** -- `cursor`: Optional pagination cursor from a previous request's nextCursor. - -**Returns:** -- mcp.types.ListResourceTemplatesResult: The complete response object from the protocol, -containing the list of resource templates and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `list_resource_templates` - -```python -list_resource_templates(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.ResourceTemplate] -``` - -Retrieve all resource templates available on the server. - -This method automatically fetches all pages if the server paginates results, -returning the complete list. For manual pagination control (e.g., to handle -large result sets incrementally), use list_resource_templates_mcp() with the -cursor parameter. - -**Args:** -- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250. - -**Returns:** -- list\[mcp.types.ResourceTemplate]: A list of all ResourceTemplate objects. - -**Raises:** -- `RuntimeError`: If the page limit is reached before pagination completes. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `read_resource_mcp` - -```python -read_resource_mcp(self: Client, uri: AnyUrl | str, meta: dict[str, Any] | None = None) -> mcp.types.ReadResourceResult -``` - -Send a resources/read request and return the complete MCP protocol result. - -**Args:** -- `uri`: The URI of the resource to read. Can be a string or an AnyUrl object. -- `meta`: Request metadata (e.g., for SEP-1686 tasks). Defaults to None. - -**Returns:** -- mcp.types.ReadResourceResult: The complete response object from the protocol, -containing the resource contents and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `read_resource` - -```python -read_resource(self: Client, uri: AnyUrl | str) -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] -``` - -#### `read_resource` - -```python -read_resource(self: Client, uri: AnyUrl | str) -> ResourceTask -``` - -#### `read_resource` - -```python -read_resource(self: Client, uri: AnyUrl | str) -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] | ResourceTask -``` - -Read the contents of a resource or resolved template. - -**Args:** -- `uri`: The URI of the resource to read. Can be a string or an AnyUrl object. -- `version`: Specific version to read. If None, reads highest version. -- `meta`: Optional request-level metadata. -- `task`: If True, execute as background task (SEP-1686). Defaults to False. -- `task_id`: Optional client-provided task ID (auto-generated if not provided). -- `ttl`: Time to keep results available in milliseconds (default 60s). - -**Returns:** -- list\[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] | ResourceTask: -A list of content objects if task=False, or a ResourceTask object if task=True. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - diff --git a/docs/python-sdk/fastmcp-client-mixins-task_management.mdx b/docs/python-sdk/fastmcp-client-mixins-task_management.mdx deleted file mode 100644 index 90d6d18b8..000000000 --- a/docs/python-sdk/fastmcp-client-mixins-task_management.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: task_management -sidebarTitle: task_management ---- - -# `fastmcp.client.mixins.task_management` - - -Task management methods for FastMCP Client. - -## Classes - -### `ClientTaskManagementMixin` - - -Mixin providing task management methods for Client. - - -**Methods:** - -#### `get_task_status` - -```python -get_task_status(self: Client, task_id: str) -> GetTaskResult -``` - -Query the status of a background task. - -Sends a 'tasks/get' MCP protocol request over the existing transport. - -**Args:** -- `task_id`: The task ID returned from call_tool_as_task - -**Returns:** -- Status information including taskId, status, pollInterval, etc. - -**Raises:** -- `RuntimeError`: If client not connected -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `get_task_result` - -```python -get_task_result(self: Client, task_id: str) -> Any -``` - -Retrieve the raw result of a completed background task. - -Sends a 'tasks/result' MCP protocol request over the existing transport. -Returns the raw result - callers should parse it appropriately. - -**Args:** -- `task_id`: The task ID returned from call_tool_as_task - -**Returns:** -- The raw result (could be tool, prompt, or resource result) - -**Raises:** -- `RuntimeError`: If client not connected, task not found, or task failed -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `list_tasks` - -```python -list_tasks(self: Client, cursor: str | None = None, limit: int = 50) -> dict[str, Any] -``` - -List background tasks. - -Sends a 'tasks/list' MCP protocol request to the server. If the server -returns an empty list (indicating client-side tracking), falls back to -querying status for locally tracked task IDs. - -**Args:** -- `cursor`: Optional pagination cursor -- `limit`: Maximum number of tasks to return (default 50) - -**Returns:** -- Response with structure: -- tasks: List of task status dicts with taskId, status, etc. -- nextCursor: Optional cursor for next page - -**Raises:** -- `RuntimeError`: If client not connected -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `cancel_task` - -```python -cancel_task(self: Client, task_id: str) -> mcp.types.CancelTaskResult -``` - -Cancel a task, transitioning it to cancelled state. - -Sends a 'tasks/cancel' MCP protocol request. Task will halt execution -and transition to cancelled state. - -**Args:** -- `task_id`: The task ID to cancel - -**Returns:** -- The task status showing cancelled state - -**Raises:** -- `RuntimeError`: If task doesn't exist -- `McpError`: If the request results in a TimeoutError | JSONRPCError - diff --git a/docs/python-sdk/fastmcp-client-mixins-tools.mdx b/docs/python-sdk/fastmcp-client-mixins-tools.mdx deleted file mode 100644 index 14e4c208a..000000000 --- a/docs/python-sdk/fastmcp-client-mixins-tools.mdx +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: tools -sidebarTitle: tools ---- - -# `fastmcp.client.mixins.tools` - - -Tool-related methods for FastMCP Client. - -## Classes - -### `ClientToolsMixin` - - -Mixin providing tool-related methods for Client. - - -**Methods:** - -#### `list_tools_mcp` - -```python -list_tools_mcp(self: Client) -> mcp.types.ListToolsResult -``` - -Send a tools/list request and return the complete MCP protocol result. - -**Args:** -- `cursor`: Optional pagination cursor from a previous request's nextCursor. - -**Returns:** -- mcp.types.ListToolsResult: The complete response object from the protocol, -containing the list of tools and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `list_tools` - -```python -list_tools(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.Tool] -``` - -Retrieve all tools available on the server. - -This method automatically fetches all pages if the server paginates results, -returning the complete list. For manual pagination control (e.g., to handle -large result sets incrementally), use list_tools_mcp() with the cursor parameter. - -**Args:** -- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250. - -**Returns:** -- list\[mcp.types.Tool]: A list of all Tool objects. - -**Raises:** -- `RuntimeError`: If the page limit is reached before pagination completes. -- `McpError`: If the request results in a TimeoutError | JSONRPCError - - -#### `call_tool_mcp` - -```python -call_tool_mcp(self: Client, name: str, arguments: dict[str, Any], progress_handler: ProgressHandler | None = None, timeout: datetime.timedelta | float | int | None = None, meta: dict[str, Any] | None = None) -> mcp.types.CallToolResult -``` - -Send a tools/call request and return the complete MCP protocol result. - -This method returns the raw CallToolResult object, which includes an isError flag -and other metadata. It does not raise an exception if the tool call results in an error. - -**Args:** -- `name`: The name of the tool to call. -- `arguments`: Arguments to pass to the tool. -- `timeout`: The timeout for the tool call. Defaults to None. -- `progress_handler`: The progress handler to use for the tool call. Defaults to None. -- `meta`: Additional metadata to include with the request. -This is useful for passing contextual information (like user IDs, trace IDs, or preferences) -that shouldn't be tool arguments but may influence server-side processing. The server -can access this via `context.request_context.meta`. Defaults to None. - -**Returns:** -- mcp.types.CallToolResult: The complete response object from the protocol, -containing the tool result and any additional metadata. - -**Raises:** -- `RuntimeError`: If called while the client is not connected. -- `McpError`: If the tool call requests results in a TimeoutError | JSONRPCError - - -#### `call_tool` - -```python -call_tool(self: Client, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult -``` - -#### `call_tool` - -```python -call_tool(self: Client, name: str, arguments: dict[str, Any] | None = None) -> ToolTask -``` - -#### `call_tool` - -```python -call_tool(self: Client, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult | ToolTask -``` - -Call a tool on the server. - -Unlike call_tool_mcp, this method raises a ToolError if the tool call results in an error. - -**Args:** -- `name`: The name of the tool to call. -- `arguments`: Arguments to pass to the tool. Defaults to None. -- `version`: Specific tool version to call. If None, calls highest version. -- `timeout`: The timeout for the tool call. Defaults to None. -- `progress_handler`: The progress handler to use for the tool call. Defaults to None. -- `raise_on_error`: Whether to raise an exception if the tool call results in an error. Defaults to True. -- `meta`: Additional metadata to include with the request. -This is useful for passing contextual information (like user IDs, trace IDs, or preferences) -that shouldn't be tool arguments but may influence server-side processing. The server -can access this via `context.request_context.meta`. Defaults to None. -- `task`: If True, execute as background task (SEP-1686). Defaults to False. -- `task_id`: Optional client-provided task ID (auto-generated if not provided). -- `ttl`: Time to keep results available in milliseconds (default 60s). - -**Returns:** -- CallToolResult | ToolTask: The content returned by the tool if task=False, -or a ToolTask object if task=True. If the tool returns structured -outputs, they are returned as a dataclass (if an output schema -is available) or a dictionary; otherwise, a list of content -blocks is returned. Note: to receive both structured and -unstructured outputs, use call_tool_mcp instead and access the -raw result object. - -**Raises:** -- `ToolError`: If the tool call results in an error. -- `McpError`: If the tool call request results in a TimeoutError | JSONRPCError -- `RuntimeError`: If called while the client is not connected. - diff --git a/docs/python-sdk/fastmcp-client-oauth_callback.mdx b/docs/python-sdk/fastmcp-client-oauth_callback.mdx deleted file mode 100644 index c3e3e84fb..000000000 --- a/docs/python-sdk/fastmcp-client-oauth_callback.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: oauth_callback -sidebarTitle: oauth_callback ---- - -# `fastmcp.client.oauth_callback` - - - -OAuth callback server for handling authorization code flows. - -This module provides a reusable callback server that can handle OAuth redirects -and display styled responses to users. - - -## Functions - -### `create_callback_html` - -```python -create_callback_html(message: str, is_success: bool = True, title: str = 'FastMCP OAuth', server_url: str | None = None) -> str -``` - - -Create a styled HTML response for OAuth callbacks. - - -### `create_oauth_callback_server` - -```python -create_oauth_callback_server(port: int, callback_path: str = '/callback', server_url: str | None = None, result_container: OAuthCallbackResult | None = None, result_ready: anyio.Event | None = None) -> Server -``` - - -Create an OAuth callback server. - -**Args:** -- `port`: The port to run the server on -- `callback_path`: The path to listen for OAuth redirects on -- `server_url`: Optional server URL to display in success messages -- `result_container`: Optional container to store callback results -- `result_ready`: Optional event to signal when callback is received - -**Returns:** -- Configured uvicorn Server instance (not yet running) - - -## Classes - -### `CallbackResponse` - -**Methods:** - -#### `from_dict` - -```python -from_dict(cls, data: dict[str, str]) -> CallbackResponse -``` - -#### `to_dict` - -```python -to_dict(self) -> dict[str, str] -``` - -### `OAuthCallbackResult` - - -Container for OAuth callback results, used with anyio.Event for async coordination. - diff --git a/docs/python-sdk/fastmcp-client-progress.mdx b/docs/python-sdk/fastmcp-client-progress.mdx deleted file mode 100644 index 884dab165..000000000 --- a/docs/python-sdk/fastmcp-client-progress.mdx +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: progress -sidebarTitle: progress ---- - -# `fastmcp.client.progress` - -## Functions - -### `default_progress_handler` - -```python -default_progress_handler(progress: float, total: float | None, message: str | None) -> None -``` - - -Default handler for progress notifications. - -Logs progress updates at debug level, properly handling missing total or message values. - -**Args:** -- `progress`: Current progress value -- `total`: Optional total expected value -- `message`: Optional status message - diff --git a/docs/python-sdk/fastmcp-client-roots.mdx b/docs/python-sdk/fastmcp-client-roots.mdx deleted file mode 100644 index 8b429856a..000000000 --- a/docs/python-sdk/fastmcp-client-roots.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: roots -sidebarTitle: roots ---- - -# `fastmcp.client.roots` - -## Functions - -### `convert_roots_list` - -```python -convert_roots_list(roots: RootsList) -> list[mcp.types.Root] -``` - -### `create_roots_callback` - -```python -create_roots_callback(handler: RootsList | RootsHandler) -> ListRootsFnT -``` diff --git a/docs/python-sdk/fastmcp-client-sampling-__init__.mdx b/docs/python-sdk/fastmcp-client-sampling-__init__.mdx deleted file mode 100644 index 609853b1f..000000000 --- a/docs/python-sdk/fastmcp-client-sampling-__init__.mdx +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.client.sampling` - -## Functions - -### `create_sampling_callback` - -```python -create_sampling_callback(sampling_handler: SamplingHandler) -> SamplingFnT -``` diff --git a/docs/python-sdk/fastmcp-client-sampling-handlers-__init__.mdx b/docs/python-sdk/fastmcp-client-sampling-handlers-__init__.mdx deleted file mode 100644 index 43329b5e6..000000000 --- a/docs/python-sdk/fastmcp-client-sampling-handlers-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.client.sampling.handlers` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-client-sampling-handlers-anthropic.mdx b/docs/python-sdk/fastmcp-client-sampling-handlers-anthropic.mdx deleted file mode 100644 index ff48e7a31..000000000 --- a/docs/python-sdk/fastmcp-client-sampling-handlers-anthropic.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: anthropic -sidebarTitle: anthropic ---- - -# `fastmcp.client.sampling.handlers.anthropic` - - -Anthropic sampling handler for FastMCP. - -## Classes - -### `AnthropicSamplingHandler` - - -Sampling handler that uses the Anthropic API. - diff --git a/docs/python-sdk/fastmcp-client-sampling-handlers-google_genai.mdx b/docs/python-sdk/fastmcp-client-sampling-handlers-google_genai.mdx deleted file mode 100644 index d55619c72..000000000 --- a/docs/python-sdk/fastmcp-client-sampling-handlers-google_genai.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: google_genai -sidebarTitle: google_genai ---- - -# `fastmcp.client.sampling.handlers.google_genai` - - -Google GenAI sampling handler with tool support for FastMCP 3.0. - -## Classes - -### `GoogleGenaiSamplingHandler` - - -Sampling handler that uses the Google GenAI API with tool support. - diff --git a/docs/python-sdk/fastmcp-client-sampling-handlers-openai.mdx b/docs/python-sdk/fastmcp-client-sampling-handlers-openai.mdx deleted file mode 100644 index 2d7976e0f..000000000 --- a/docs/python-sdk/fastmcp-client-sampling-handlers-openai.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: openai -sidebarTitle: openai ---- - -# `fastmcp.client.sampling.handlers.openai` - - -OpenAI sampling handler for FastMCP. - -## Classes - -### `OpenAISamplingHandler` - - -Sampling handler that uses the OpenAI API. - diff --git a/docs/python-sdk/fastmcp-client-tasks.mdx b/docs/python-sdk/fastmcp-client-tasks.mdx deleted file mode 100644 index fe2cb8b40..000000000 --- a/docs/python-sdk/fastmcp-client-tasks.mdx +++ /dev/null @@ -1,219 +0,0 @@ ---- -title: tasks -sidebarTitle: tasks ---- - -# `fastmcp.client.tasks` - - -SEP-1686 client Task classes. - -## Classes - -### `TaskNotificationHandler` - - -MessageHandler that routes task status notifications to Task objects. - - -**Methods:** - -#### `dispatch` - -```python -dispatch(self, message: Message) -> None -``` - -Dispatch messages, including task status notifications. - - -### `Task` - - -Abstract base class for MCP background tasks (SEP-1686). - -Provides a uniform API whether the server accepts background execution -or executes synchronously (graceful degradation per SEP-1686). - - -**Methods:** - -#### `task_id` - -```python -task_id(self) -> str -``` - -Get the task ID. - - -#### `returned_immediately` - -```python -returned_immediately(self) -> bool -``` - -Check if server executed the task immediately. - -**Returns:** -- True if server executed synchronously (graceful degradation or no task support) -- False if server accepted background execution - - -#### `on_status_change` - -```python -on_status_change(self, callback: Callable[[GetTaskResult], None | Awaitable[None]]) -> None -``` - -Register callback for status change notifications. - -The callback will be invoked when a notifications/tasks/status is received -for this task (optional server feature per SEP-1686 lines 436-444). - -Supports both sync and async callbacks (auto-detected). - -**Args:** -- `callback`: Function to call with GetTaskResult when status changes. - Can return None (sync) or Awaitable[None] (async). - - -#### `status` - -```python -status(self) -> GetTaskResult -``` - -Get current task status. - -If server executed immediately, returns synthetic completed status. -Otherwise queries the server for current status. - - -#### `result` - -```python -result(self) -> TaskResultT -``` - -Wait for and return the task result. - -Must be implemented by subclasses to return the appropriate result type. - - -#### `wait` - -```python -wait(self) -> GetTaskResult -``` - -Wait for task to reach a specific state or complete. - -Uses event-based waiting when notifications are available (fast), -with fallback to polling (reliable). Optimally wakes up immediately -on status changes when server sends notifications/tasks/status. - -**Args:** -- `state`: Desired state ('working', 'input_required', 'completed', 'failed', 'cancelled'). - If None, waits until the task exits the 'working' state (completed, failed, cancelled, input_required, etc.) -- `timeout`: Maximum time to wait in seconds - -**Returns:** -- Final task status - -**Raises:** -- `TimeoutError`: If desired state not reached within timeout - - -#### `cancel` - -```python -cancel(self) -> None -``` - -Cancel this task, transitioning it to cancelled state. - -Sends a tasks/cancel protocol request. The server will attempt to halt -execution and move the task to cancelled state. - -Note: If server executed immediately (graceful degradation), this is a no-op -as there's no server-side task to cancel. - - -### `ToolTask` - - -Represents a tool call that may execute in background or immediately. - -Provides a uniform API whether the server accepts background execution -or executes synchronously (graceful degradation per SEP-1686). - - -**Methods:** - -#### `result` - -```python -result(self) -> CallToolResult -``` - -Wait for and return the tool result. - -If server executed immediately, returns the immediate result. -Otherwise waits for background task to complete and retrieves result. - -**Returns:** -- The parsed tool result (same as call_tool returns) - - -### `PromptTask` - - -Represents a prompt call that may execute in background or immediately. - -Provides a uniform API whether the server accepts background execution -or executes synchronously (graceful degradation per SEP-1686). - - -**Methods:** - -#### `result` - -```python -result(self) -> mcp.types.GetPromptResult -``` - -Wait for and return the prompt result. - -If server executed immediately, returns the immediate result. -Otherwise waits for background task to complete and retrieves result. - -**Returns:** -- The prompt result with messages and description - - -### `ResourceTask` - - -Represents a resource read that may execute in background or immediately. - -Provides a uniform API whether the server accepts background execution -or executes synchronously (graceful degradation per SEP-1686). - - -**Methods:** - -#### `result` - -```python -result(self) -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] -``` - -Wait for and return the resource contents. - -If server executed immediately, returns the immediate result. -Otherwise waits for background task to complete and retrieves result. - -**Returns:** -- list\[ReadResourceContents]: The resource contents - diff --git a/docs/python-sdk/fastmcp-client-telemetry.mdx b/docs/python-sdk/fastmcp-client-telemetry.mdx deleted file mode 100644 index 843d97631..000000000 --- a/docs/python-sdk/fastmcp-client-telemetry.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: telemetry -sidebarTitle: telemetry ---- - -# `fastmcp.client.telemetry` - - -Client-side telemetry helpers. - -## Functions - -### `client_span` - -```python -client_span(name: str, method: str, component_key: str, session_id: str | None = None, resource_uri: str | None = None, tool_name: str | None = None, prompt_name: str | None = None) -> Generator[Span, None, None] -``` - - -Create a CLIENT span with standard MCP attributes. - -Automatically records any exception on the span and sets error status. - diff --git a/docs/python-sdk/fastmcp-client-transports-__init__.mdx b/docs/python-sdk/fastmcp-client-transports-__init__.mdx deleted file mode 100644 index 1f9b02d38..000000000 --- a/docs/python-sdk/fastmcp-client-transports-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.client.transports` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-client-transports-base.mdx b/docs/python-sdk/fastmcp-client-transports-base.mdx deleted file mode 100644 index 12c1848d2..000000000 --- a/docs/python-sdk/fastmcp-client-transports-base.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: base -sidebarTitle: base ---- - -# `fastmcp.client.transports.base` - -## Classes - -### `SessionKwargs` - - -Keyword arguments for the MCP ClientSession constructor. - - -### `ClientTransport` - - -Abstract base class for different MCP client transport mechanisms. - -A Transport is responsible for establishing and managing connections -to an MCP server, and providing a ClientSession within an async context. - - -**Methods:** - -#### `connect_session` - -```python -connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] -``` - -Establishes a connection and yields an active ClientSession. - -The ClientSession is *not* expected to be initialized in this context manager. - -The session is guaranteed to be valid only within the scope of the -async context manager. Connection setup and teardown are handled -within this context. - -**Args:** -- `**session_kwargs`: Keyword arguments to pass to the ClientSession - constructor (e.g., callbacks, timeouts). - - -#### `close` - -```python -close(self) -``` - -Close the transport. - - -#### `get_session_id` - -```python -get_session_id(self) -> str | None -``` - -Get the session ID for this transport, if available. - diff --git a/docs/python-sdk/fastmcp-client-transports-config.mdx b/docs/python-sdk/fastmcp-client-transports-config.mdx deleted file mode 100644 index 3881c69e1..000000000 --- a/docs/python-sdk/fastmcp-client-transports-config.mdx +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: config -sidebarTitle: config ---- - -# `fastmcp.client.transports.config` - -## Classes - -### `MCPConfigTransport` - - -Transport for connecting to one or more MCP servers defined in an MCPConfig. - -This transport provides a unified interface to multiple MCP servers defined in an MCPConfig -object or dictionary matching the MCPConfig schema. It supports two key scenarios: - -1. If the MCPConfig contains exactly one server, it creates a direct transport to that server. -2. If the MCPConfig contains multiple servers, it creates a composite client by mounting - all servers on a single FastMCP instance, with each server's name, by default, used as its mounting prefix. - -In the multiserver case, tools are accessible with the prefix pattern `{server_name}_{tool_name}` -and resources with the pattern `protocol://{server_name}/path/to/resource`. - -This is particularly useful for creating clients that need to interact with multiple specialized -MCP servers through a single interface, simplifying client code. - -**Examples:** - -```python -from fastmcp import Client - -# Create a config with multiple servers -config = { - "mcpServers": { - "weather": { - "url": "https://weather-api.example.com/mcp", - "transport": "http" - }, - "calendar": { - "url": "https://calendar-api.example.com/mcp", - "transport": "http" - } - } -} - -# Create a client with the config -client = Client(config) - -async with client: - # Access tools with prefixes - weather = await client.call_tool("weather_get_forecast", {"city": "London"}) - events = await client.call_tool("calendar_list_events", {"date": "2023-06-01"}) - - # Access resources with prefixed URIs - icons = await client.read_resource("weather://weather/icons/sunny") -``` - - -**Methods:** - -#### `connect_session` - -```python -connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] -``` - -#### `close` - -```python -close(self) -``` diff --git a/docs/python-sdk/fastmcp-client-transports-http.mdx b/docs/python-sdk/fastmcp-client-transports-http.mdx deleted file mode 100644 index 48a9559e3..000000000 --- a/docs/python-sdk/fastmcp-client-transports-http.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: http -sidebarTitle: http ---- - -# `fastmcp.client.transports.http` - - -Streamable HTTP transport for FastMCP Client. - -## Classes - -### `StreamableHttpTransport` - - -Transport implementation that connects to an MCP server via Streamable HTTP Requests. - - -**Methods:** - -#### `connect_session` - -```python -connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] -``` - -#### `get_session_id` - -```python -get_session_id(self) -> str | None -``` - -#### `close` - -```python -close(self) -``` diff --git a/docs/python-sdk/fastmcp-client-transports-inference.mdx b/docs/python-sdk/fastmcp-client-transports-inference.mdx deleted file mode 100644 index 730f56845..000000000 --- a/docs/python-sdk/fastmcp-client-transports-inference.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: inference -sidebarTitle: inference ---- - -# `fastmcp.client.transports.inference` - -## Functions - -### `infer_transport` - -```python -infer_transport(transport: ClientTransport | FastMCP | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str) -> ClientTransport -``` - - -Infer the appropriate transport type from the given transport argument. - -This function attempts to infer the correct transport type from the provided -argument, handling various input types and converting them to the appropriate -ClientTransport subclass. - -The function supports these input types: -- ClientTransport: Used directly without modification -- FastMCP or FastMCP1Server: Creates an in-memory FastMCPTransport -- Path or str (file path): Creates PythonStdioTransport (.py) or NodeStdioTransport (.js) -- AnyUrl or str (URL): Creates StreamableHttpTransport (default) or SSETransport (for /sse endpoints) -- MCPConfig or dict: Creates MCPConfigTransport, potentially connecting to multiple servers - -For HTTP URLs, they are assumed to be Streamable HTTP URLs unless they end in `/sse`. - -For MCPConfig with multiple servers, a composite client is created where each server -is mounted with its name as prefix. This allows accessing tools and resources from multiple -servers through a single unified client interface, using naming patterns like -`servername_toolname` for tools and `protocol://servername/path` for resources. -If the MCPConfig contains only one server, a direct connection is established without prefixing. - -**Examples:** - -```python -# Connect to a local Python script -transport = infer_transport("my_script.py") - -# Connect to a remote server via HTTP -transport = infer_transport("http://example.com/mcp") - -# Connect to multiple servers using MCPConfig -config = { - "mcpServers": { - "weather": {"url": "http://weather.example.com/mcp"}, - "calendar": {"url": "http://calendar.example.com/mcp"} - } -} -transport = infer_transport(config) -``` - diff --git a/docs/python-sdk/fastmcp-client-transports-memory.mdx b/docs/python-sdk/fastmcp-client-transports-memory.mdx deleted file mode 100644 index b5887b8ca..000000000 --- a/docs/python-sdk/fastmcp-client-transports-memory.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: memory -sidebarTitle: memory ---- - -# `fastmcp.client.transports.memory` - -## Classes - -### `FastMCPTransport` - - -In-memory transport for FastMCP servers. - -This transport connects directly to a FastMCP server instance in the same -Python process. It works with both FastMCP 2.x servers and FastMCP 1.0 -servers from the low-level MCP SDK. This is particularly useful for unit -tests or scenarios where client and server run in the same runtime. - - -**Methods:** - -#### `connect_session` - -```python -connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] -``` diff --git a/docs/python-sdk/fastmcp-client-transports-sse.mdx b/docs/python-sdk/fastmcp-client-transports-sse.mdx deleted file mode 100644 index 6a78d9325..000000000 --- a/docs/python-sdk/fastmcp-client-transports-sse.mdx +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: sse -sidebarTitle: sse ---- - -# `fastmcp.client.transports.sse` - - -Server-Sent Events (SSE) transport for FastMCP Client. - -## Classes - -### `SSETransport` - - -Transport implementation that connects to an MCP server via Server-Sent Events. - - -**Methods:** - -#### `connect_session` - -```python -connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] -``` diff --git a/docs/python-sdk/fastmcp-client-transports-stdio.mdx b/docs/python-sdk/fastmcp-client-transports-stdio.mdx deleted file mode 100644 index ac317bfc3..000000000 --- a/docs/python-sdk/fastmcp-client-transports-stdio.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: stdio -sidebarTitle: stdio ---- - -# `fastmcp.client.transports.stdio` - -## Classes - -### `StdioTransport` - - -Base transport for connecting to an MCP server via subprocess with stdio. - -This is a base class that can be subclassed for specific command-based -transports like Python, Node, Uvx, etc. - - -**Methods:** - -#### `connect_session` - -```python -connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] -``` - -#### `connect` - -```python -connect(self, **session_kwargs: Unpack[SessionKwargs]) -> ClientSession | None -``` - -#### `disconnect` - -```python -disconnect(self) -``` - -#### `close` - -```python -close(self) -``` - -### `PythonStdioTransport` - - -Transport for running Python scripts. - - -### `FastMCPStdioTransport` - - -Transport for running FastMCP servers using the FastMCP CLI. - - -### `NodeStdioTransport` - - -Transport for running Node.js scripts. - - -### `UvStdioTransport` - - -Transport for running commands via the uv tool. - - -### `UvxStdioTransport` - - -Transport for running commands via the uvx tool. - - -### `NpxStdioTransport` - - -Transport for running commands via the npx tool. - diff --git a/docs/python-sdk/fastmcp-client-__init__.mdx b/docs/python-sdk/fastmcp-client.mdx similarity index 72% rename from docs/python-sdk/fastmcp-client-__init__.mdx rename to docs/python-sdk/fastmcp-client.mdx index bc145d4b7..5e1b78ef7 100644 --- a/docs/python-sdk/fastmcp-client-__init__.mdx +++ b/docs/python-sdk/fastmcp-client.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: client +sidebarTitle: client --- # `fastmcp.client` diff --git a/docs/python-sdk/fastmcp-decorators.mdx b/docs/python-sdk/fastmcp-decorators.mdx index c2cc11dbb..0eb68b25a 100644 --- a/docs/python-sdk/fastmcp-decorators.mdx +++ b/docs/python-sdk/fastmcp-decorators.mdx @@ -10,7 +10,7 @@ Shared decorator utilities for FastMCP. ## Functions -### `resolve_task_config` +### `resolve_task_config` ```python resolve_task_config(task: bool | TaskConfig | None) -> bool | TaskConfig @@ -20,7 +20,7 @@ resolve_task_config(task: bool | TaskConfig | None) -> bool | TaskConfig Resolve task config, defaulting None to False. -### `get_fastmcp_meta` +### `get_fastmcp_meta` ```python get_fastmcp_meta(fn: Any) -> Any | None @@ -32,7 +32,7 @@ Extract FastMCP metadata from a function, handling bound methods and wrappers. ## Classes -### `HasFastMCPMeta` +### `HasFastMCPMeta` Protocol for callables decorated with FastMCP metadata. diff --git a/docs/python-sdk/fastmcp-exceptions.mdx b/docs/python-sdk/fastmcp-exceptions.mdx index e662031a0..eb554c3fe 100644 --- a/docs/python-sdk/fastmcp-exceptions.mdx +++ b/docs/python-sdk/fastmcp-exceptions.mdx @@ -10,7 +10,7 @@ Custom exceptions for FastMCP. ## Classes -### `FastMCPDeprecationWarning` +### `FastMCPDeprecationWarning` Deprecation warning for FastMCP APIs. @@ -20,61 +20,61 @@ still apply, but FastMCP can selectively enable its own warnings without affecting other libraries in the process. -### `FastMCPError` +### `FastMCPError` Base error for FastMCP. -### `ValidationError` +### `ValidationError` Error in validating parameters or return values. -### `ResourceError` +### `ResourceError` Error in resource operations. -### `ToolError` +### `ToolError` Error in tool operations. -### `PromptError` +### `PromptError` Error in prompt operations. -### `InvalidSignature` +### `InvalidSignature` Invalid signature for use with FastMCP. -### `ClientError` +### `ClientError` Error in client operations. -### `NotFoundError` +### `NotFoundError` Object not found. -### `DisabledError` +### `DisabledError` Object is disabled. -### `AuthorizationError` +### `AuthorizationError` Error when authorization check fails. diff --git a/docs/python-sdk/fastmcp-experimental-transforms-code_mode.mdx b/docs/python-sdk/fastmcp-experimental-transforms-code_mode.mdx index 4b954336b..ae98a1a4d 100644 --- a/docs/python-sdk/fastmcp-experimental-transforms-code_mode.mdx +++ b/docs/python-sdk/fastmcp-experimental-transforms-code_mode.mdx @@ -7,7 +7,7 @@ sidebarTitle: code_mode ## Classes -### `SandboxProvider` +### `SandboxProvider` Interface for executing LLM-generated Python code in a sandbox. @@ -20,13 +20,13 @@ sandbox — never with plain ``exec()``. Use ``MontySandboxProvider`` **Methods:** -#### `run` +#### `run` ```python run(self, code: str) -> Any ``` -### `MontySandboxProvider` +### `MontySandboxProvider` Sandbox provider backed by `pydantic-monty`. @@ -41,13 +41,13 @@ leave that limit uncapped. **Methods:** -#### `run` +#### `run` ```python run(self, code: str) -> Any ``` -### `Search` +### `Search` Discovery tool factory that searches the catalog by query. @@ -64,7 +64,7 @@ Defaults to BM25 ranking. The LLM can override this per call. ``None`` means no limit. -### `GetSchemas` +### `GetSchemas` Discovery tool factory that returns schemas for tools by name. @@ -78,7 +78,7 @@ types, and required markers. ``"full"`` returns the complete JSON schema. -### `GetTags` +### `GetTags` Discovery tool factory that lists tool tags from the catalog. @@ -93,7 +93,7 @@ without tags appear under ``"untagged"``. ``"full"`` lists all tools under each tag. -### `ListTools` +### `ListTools` Discovery tool factory that lists all tools in the catalog. @@ -106,7 +106,7 @@ Discovery tool factory that lists all tools in the catalog. ``"full"`` returns the complete JSON schema. -### `CodeMode` +### `CodeMode` Transform that collapses all tools into discovery + execute meta-tools. @@ -123,13 +123,13 @@ environment with ``call_tool(name, params)`` in scope. **Methods:** -#### `transform_tools` +#### `transform_tools` ```python transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] ``` -#### `get_tool` +#### `get_tool` ```python get_tool(self, name: str, call_next: GetToolNext) -> Tool | None diff --git a/docs/python-sdk/fastmcp-mcp_config.mdx b/docs/python-sdk/fastmcp-mcp_config.mdx index f7d8f6e26..8d0c4a83e 100644 --- a/docs/python-sdk/fastmcp-mcp_config.mdx +++ b/docs/python-sdk/fastmcp-mcp_config.mdx @@ -32,7 +32,7 @@ Example configuration: ## Functions -### `infer_transport_type_from_url` +### `infer_transport_type_from_url` ```python infer_transport_type_from_url(url: str | AnyUrl) -> Literal['http', 'sse'] @@ -42,7 +42,7 @@ infer_transport_type_from_url(url: str | AnyUrl) -> Literal['http', 'sse'] Infer the appropriate transport type from the given URL. -### `update_config_file` +### `update_config_file` ```python update_config_file(file_path: Path, server_name: str, server_config: CanonicalMCPServerTypes) -> None @@ -57,7 +57,7 @@ worry about transforming server objects here. ## Classes -### `StdioMCPServer` +### `StdioMCPServer` MCP server configuration for stdio transport. @@ -67,19 +67,19 @@ This is the canonical configuration format for MCP servers using stdio transport **Methods:** -#### `to_transport` +#### `to_transport` ```python to_transport(self) -> StdioTransport ``` -### `TransformingStdioMCPServer` +### `TransformingStdioMCPServer` A Stdio server with tool transforms. -### `RemoteMCPServer` +### `RemoteMCPServer` MCP server configuration for HTTP/SSE transport. @@ -89,19 +89,19 @@ This is the canonical configuration format for MCP servers using remote transpor **Methods:** -#### `to_transport` +#### `to_transport` ```python to_transport(self) -> StreamableHttpTransport | SSETransport ``` -### `TransformingRemoteMCPServer` +### `TransformingRemoteMCPServer` A Remote server with tool transforms. -### `MCPConfig` +### `MCPConfig` A configuration object for MCP Servers that conforms to the canonical MCP configuration format @@ -113,7 +113,7 @@ For an MCPConfig that is strictly canonical, see the `CanonicalMCPConfig` class. **Methods:** -#### `wrap_servers_at_root` +#### `wrap_servers_at_root` ```python wrap_servers_at_root(cls, values: dict[str, Any]) -> dict[str, Any] @@ -122,7 +122,7 @@ wrap_servers_at_root(cls, values: dict[str, Any]) -> dict[str, Any] If there's no mcpServers key but there are server configs at root, wrap them. -#### `add_server` +#### `add_server` ```python add_server(self, name: str, server: MCPServerTypes) -> None @@ -131,7 +131,7 @@ add_server(self, name: str, server: MCPServerTypes) -> None Add or update a server in the configuration. -#### `from_dict` +#### `from_dict` ```python from_dict(cls, config: dict[str, Any]) -> Self @@ -140,7 +140,7 @@ from_dict(cls, config: dict[str, Any]) -> Self Parse MCP configuration from dictionary format. -#### `to_dict` +#### `to_dict` ```python to_dict(self) -> dict[str, Any] @@ -149,7 +149,7 @@ to_dict(self) -> dict[str, Any] Convert MCPConfig to dictionary format, preserving all fields. -#### `write_to_file` +#### `write_to_file` ```python write_to_file(self, file_path: Path) -> None @@ -158,7 +158,7 @@ write_to_file(self, file_path: Path) -> None Write configuration to JSON file. -#### `from_file` +#### `from_file` ```python from_file(cls, file_path: Path) -> Self @@ -167,7 +167,7 @@ from_file(cls, file_path: Path) -> Self Load configuration from JSON file. -### `CanonicalMCPConfig` +### `CanonicalMCPConfig` Canonical MCP configuration format. @@ -178,7 +178,7 @@ The format is designed to be client-agnostic and extensible for future use cases **Methods:** -#### `add_server` +#### `add_server` ```python add_server(self, name: str, server: CanonicalMCPServerTypes) -> None diff --git a/docs/python-sdk/fastmcp-prompts-base.mdx b/docs/python-sdk/fastmcp-prompts-base.mdx deleted file mode 100644 index 1c57fbea2..000000000 --- a/docs/python-sdk/fastmcp-prompts-base.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: base -sidebarTitle: base ---- - -# `fastmcp.prompts.base` - - -Base classes for FastMCP prompts. - -## Classes - -### `Message` - - -Wrapper for prompt message with auto-serialization. - -Accepts any content - strings pass through, other types -(dict, list, BaseModel) are JSON-serialized to text. - - -**Methods:** - -#### `to_mcp_prompt_message` - -```python -to_mcp_prompt_message(self) -> PromptMessage -``` - -Convert to MCP PromptMessage. - - -### `PromptArgument` - - -An argument that can be passed to a prompt. - - -### `PromptResult` - - -Canonical result type for prompt rendering. - -Provides explicit control over prompt responses: multiple messages, -roles, and metadata at both the message and result level. - - -**Methods:** - -#### `to_mcp_prompt_result` - -```python -to_mcp_prompt_result(self) -> GetPromptResult -``` - -Convert to MCP GetPromptResult. - - -### `Prompt` - - -A prompt template that can be rendered with parameters. - - -**Methods:** - -#### `to_mcp_prompt` - -```python -to_mcp_prompt(self, **overrides: Any) -> SDKPrompt -``` - -Convert the prompt to an MCP prompt. - - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any]) -> FunctionPrompt -``` - -Create a Prompt from a function. - -The function can return: -- str: wrapped as single user Message -- list\[Message | str]: converted to list\[Message] -- PromptResult: used directly - - -#### `render` - -```python -render(self, arguments: dict[str, Any] | None = None) -> str | list[Message | str] | PromptResult -``` - -Render the prompt with arguments. - -Subclasses must implement this method. Return one of: -- str: Wrapped as single user Message -- list\[Message | str]: Converted to list\[Message] -- PromptResult: Used directly - - -#### `convert_result` - -```python -convert_result(self, raw_value: Any) -> PromptResult -``` - -Convert a raw return value to PromptResult. - -**Raises:** -- `TypeError`: for unsupported types - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this prompt with docket for background execution. - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, arguments: dict[str, Any] | None, **kwargs: Any) -> Execution -``` - -Schedule this prompt for background execution via docket. - -**Args:** -- `docket`: The Docket instance -- `arguments`: Prompt arguments -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` diff --git a/docs/python-sdk/fastmcp-prompts-function_prompt.mdx b/docs/python-sdk/fastmcp-prompts-function_prompt.mdx deleted file mode 100644 index 52082d732..000000000 --- a/docs/python-sdk/fastmcp-prompts-function_prompt.mdx +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: function_prompt -sidebarTitle: function_prompt ---- - -# `fastmcp.prompts.function_prompt` - - -Standalone @prompt decorator for FastMCP. - -## Functions - -### `prompt` - -```python -prompt(name_or_fn: str | Callable[..., Any] | None = None) -> Any -``` - - -Standalone decorator to mark a function as an MCP prompt. - -Returns the original function with metadata attached. Register with a server -using mcp.add_prompt(). - - -## Classes - -### `DecoratedPrompt` - - -Protocol for functions decorated with @prompt. - - -### `PromptMeta` - - -Metadata attached to functions by the @prompt decorator. - - -### `FunctionPrompt` - - -A prompt that is a function. - - -**Methods:** - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any]) -> FunctionPrompt -``` - -Create a Prompt from a function. - -**Args:** -- `fn`: The function to wrap -- `metadata`: PromptMeta object with all configuration. If provided, -individual parameters must not be passed. -- `name, title, etc.`: Individual parameters for backwards compatibility. -Cannot be used together with metadata parameter. - -The function can return: -- str: wrapped as single user Message -- list\[Message | str]: converted to list\[Message] -- PromptResult: used directly - - -#### `render` - -```python -render(self, arguments: dict[str, Any] | None = None) -> PromptResult -``` - -Render the prompt with arguments. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this prompt with docket for background execution. - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, arguments: dict[str, Any] | None, **kwargs: Any) -> Execution -``` - -Schedule this prompt for background execution via docket. - -FunctionPrompt splats the arguments dict since .fn expects **kwargs. - -**Args:** -- `docket`: The Docket instance -- `arguments`: Prompt arguments -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - diff --git a/docs/python-sdk/fastmcp-prompts-__init__.mdx b/docs/python-sdk/fastmcp-prompts.mdx similarity index 72% rename from docs/python-sdk/fastmcp-prompts-__init__.mdx rename to docs/python-sdk/fastmcp-prompts.mdx index 8ef80b59e..c20e366a9 100644 --- a/docs/python-sdk/fastmcp-prompts-__init__.mdx +++ b/docs/python-sdk/fastmcp-prompts.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: prompts +sidebarTitle: prompts --- # `fastmcp.prompts` diff --git a/docs/python-sdk/fastmcp-resources-base.mdx b/docs/python-sdk/fastmcp-resources-base.mdx deleted file mode 100644 index d9f76a057..000000000 --- a/docs/python-sdk/fastmcp-resources-base.mdx +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: base -sidebarTitle: base ---- - -# `fastmcp.resources.base` - - -Base classes and interfaces for FastMCP resources. - -## Classes - -### `ResourceContent` - - -Wrapper for resource content with optional MIME type and metadata. - -Accepts any value for content - strings and bytes pass through directly, -other types (dict, list, BaseModel, etc.) are automatically JSON-serialized. - - -**Methods:** - -#### `to_mcp_resource_contents` - -```python -to_mcp_resource_contents(self, uri: AnyUrl | str) -> mcp.types.TextResourceContents | mcp.types.BlobResourceContents -``` - -Convert to MCP resource contents type. - -**Args:** -- `uri`: The URI of the resource (required by MCP types) - -**Returns:** -- TextResourceContents for str content, BlobResourceContents for bytes - - -### `ResourceResult` - - -Canonical result type for resource reads. - -Provides explicit control over resource responses: multiple content items, -per-item MIME types, and metadata at both the item and result level. - - -**Methods:** - -#### `to_mcp_result` - -```python -to_mcp_result(self, uri: AnyUrl | str) -> mcp.types.ReadResourceResult -``` - -Convert to MCP ReadResourceResult. - -**Args:** -- `uri`: The URI of the resource (required by MCP types) - -**Returns:** -- MCP ReadResourceResult with converted contents - - -### `Resource` - - -Base class for all resources. - - -**Methods:** - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any], uri: str | AnyUrl) -> FunctionResource -``` - -#### `set_default_mime_type` - -```python -set_default_mime_type(cls, mime_type: str | None) -> str -``` - -Set default MIME type if not provided. - - -#### `set_default_name` - -```python -set_default_name(self) -> Self -``` - -Set default name from URI if not provided. - - -#### `read` - -```python -read(self) -> str | bytes | ResourceResult -``` - -Read the resource content. - -Subclasses implement this to return resource data. Supported return types: - - str: Text content - - bytes: Binary content - - ResourceResult: Full control over contents and result-level meta - - -#### `convert_result` - -```python -convert_result(self, raw_value: Any) -> ResourceResult -``` - -Convert a raw result to ResourceResult. - -This is used in two contexts: -1. In _read() to convert user function return values to ResourceResult -2. In tasks_result_handler() to convert Docket task results to ResourceResult - -Handles ResourceResult passthrough and converts raw values using -ResourceResult's normalization. When the raw value is a plain -string or bytes, the resource's own ``mime_type`` is forwarded so -that ``ui://`` resources (and others with non-default MIME types) -don't fall back to ``text/plain``. - -The resource's component-level ``meta`` (e.g. ``ui`` metadata for -MCP Apps CSP/permissions) is propagated to each content item so -that hosts can read it from the ``resources/read`` response. - - -#### `to_mcp_resource` - -```python -to_mcp_resource(self, **overrides: Any) -> SDKResource -``` - -Convert the resource to an SDKResource. - - -#### `key` - -```python -key(self) -> str -``` - -The globally unique lookup key for this resource. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this resource with docket for background execution. - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, **kwargs: Any) -> Execution -``` - -Schedule this resource for background execution via docket. - -**Args:** -- `docket`: The Docket instance -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` diff --git a/docs/python-sdk/fastmcp-resources-function_resource.mdx b/docs/python-sdk/fastmcp-resources-function_resource.mdx deleted file mode 100644 index 24aa2052c..000000000 --- a/docs/python-sdk/fastmcp-resources-function_resource.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: function_resource -sidebarTitle: function_resource ---- - -# `fastmcp.resources.function_resource` - - -Standalone @resource decorator for FastMCP. - -## Functions - -### `resource` - -```python -resource(uri: str) -> Callable[[F], F] -``` - - -Standalone decorator to mark a function as an MCP resource. - -Returns the original function with metadata attached. Register with a server -using mcp.add_resource(). - - -## Classes - -### `DecoratedResource` - - -Protocol for functions decorated with @resource. - - -### `ResourceMeta` - - -Metadata attached to functions by the @resource decorator. - - -### `FunctionResource` - - -A resource that defers data loading by wrapping a function. - -The function is only called when the resource is read, allowing for lazy loading -of potentially expensive data. This is particularly useful when listing resources, -as the function won't be called until the resource is actually accessed. - -The function can return: -- str for text content (default) -- bytes for binary content -- other types will be converted to JSON - - -**Methods:** - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any], uri: str | AnyUrl | None = None) -> FunctionResource -``` - -Create a FunctionResource from a function. - -**Args:** -- `fn`: The function to wrap -- `uri`: The URI for the resource (required if metadata not provided) -- `metadata`: ResourceMeta object with all configuration. If provided, -individual parameters must not be passed. -- `name, title, etc.`: Individual parameters for backwards compatibility. -Cannot be used together with metadata parameter. - - -#### `read` - -```python -read(self) -> str | bytes | ResourceResult -``` - -Read the resource by calling the wrapped function. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this resource with docket for background execution. - diff --git a/docs/python-sdk/fastmcp-resources-template.mdx b/docs/python-sdk/fastmcp-resources-template.mdx deleted file mode 100644 index 6c96bacaf..000000000 --- a/docs/python-sdk/fastmcp-resources-template.mdx +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: template -sidebarTitle: template ---- - -# `fastmcp.resources.template` - - -Resource template functionality. - -## Functions - -### `extract_query_params` - -```python -extract_query_params(uri_template: str) -> set[str] -``` - - -Extract query parameter names from RFC 6570 `{?param1,param2}` syntax. - - -### `build_regex` - -```python -build_regex(template: str) -> re.Pattern[str] | None -``` - - -Build regex pattern for URI template, handling RFC 6570 syntax. - -Supports: -- `{var}` - simple path parameter -- `{var*}` - wildcard path parameter (captures multiple segments) -- `{?var1,var2}` - query parameters (ignored in path matching) - -Hyphens in parameter names are normalized to underscores in regex group -names so that matched groups are valid Python identifiers. - -Returns None if the template produces an invalid regex (e.g. parameter -names with leading digits or duplicates from a remote server). - - -### `match_uri_template` - -```python -match_uri_template(uri: str, uri_template: str) -> dict[str, str] | None -``` - - -Match URI against template and extract both path and query parameters. - -Supports RFC 6570 URI templates: -- Path params: `{var}`, `{var*}` -- Query params: `{?var1,var2}` - - -### `expand_uri_template` - -```python -expand_uri_template(uri_template: str, params: dict[str, Any]) -> str -``` - - -Expand a URI template with parameters — inverse of `match_uri_template`. - -Supports the same RFC 6570 subset: -- Path params: `{var}`, `{var*}` -- Query params: `{?var1,var2}` - - -## Classes - -### `ResourceTemplate` - - -A template for dynamically creating resources. - - -**Methods:** - -#### `from_function` - -```python -from_function(fn: Callable[..., Any], uri_template: str, name: str | None = None, version: str | int | None = None, title: str | None = None, description: str | None = None, icons: list[Icon] | None = None, mime_type: str | None = None, tags: set[str] | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None, task: bool | TaskConfig | None = None, auth: AuthCheck | list[AuthCheck] | None = None) -> FunctionResourceTemplate -``` - -#### `set_default_mime_type` - -```python -set_default_mime_type(cls, mime_type: str | None) -> str -``` - -Set default MIME type if not provided. - - -#### `matches` - -```python -matches(self, uri: str) -> dict[str, Any] | None -``` - -Check if URI matches template and extract parameters. - - -#### `read` - -```python -read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult -``` - -Read the resource content. - - -#### `convert_result` - -```python -convert_result(self, raw_value: Any) -> ResourceResult -``` - -Convert a raw result to ResourceResult. - -This is used in two contexts: -1. In _read() to convert user function return values to ResourceResult -2. In tasks_result_handler() to convert Docket task results to ResourceResult - -Handles ResourceResult passthrough and converts raw values using -ResourceResult's normalization. - - -#### `create_resource` - -```python -create_resource(self, uri: str, params: dict[str, Any]) -> Resource -``` - -Create a resource from the template with the given parameters. - -The base implementation does not support background tasks. -Use FunctionResourceTemplate for task support. - - -#### `to_mcp_template` - -```python -to_mcp_template(self, **overrides: Any) -> SDKResourceTemplate -``` - -Convert the resource template to an SDKResourceTemplate. - - -#### `from_mcp_template` - -```python -from_mcp_template(cls, mcp_template: SDKResourceTemplate) -> ResourceTemplate -``` - -Creates a FastMCP ResourceTemplate from a raw MCP ResourceTemplate object. - - -#### `key` - -```python -key(self) -> str -``` - -The globally unique lookup key for this template. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this template with docket for background execution. - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, params: dict[str, Any], **kwargs: Any) -> Execution -``` - -Schedule this template for background execution via docket. - -**Args:** -- `docket`: The Docket instance -- `params`: Template parameters -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `FunctionResourceTemplate` - - -A template for dynamically creating resources. - - -**Methods:** - -#### `create_resource` - -```python -create_resource(self, uri: str, params: dict[str, Any]) -> Resource -``` - -Create a resource from the template with the given parameters. - - -#### `read` - -```python -read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult -``` - -Read the resource content. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this template with docket for background execution. - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, params: dict[str, Any], **kwargs: Any) -> Execution -``` - -Schedule this template for background execution via docket. - -FunctionResourceTemplate splats the params dict since .fn expects **kwargs. - -**Args:** -- `docket`: The Docket instance -- `params`: Template parameters -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any], uri_template: str, name: str | None = None, version: str | int | None = None, title: str | None = None, description: str | None = None, icons: list[Icon] | None = None, mime_type: str | None = None, tags: set[str] | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None, task: bool | TaskConfig | None = None, auth: AuthCheck | list[AuthCheck] | None = None) -> FunctionResourceTemplate -``` - -Create a template from a function. - diff --git a/docs/python-sdk/fastmcp-resources-types.mdx b/docs/python-sdk/fastmcp-resources-types.mdx deleted file mode 100644 index 5a951f0dc..000000000 --- a/docs/python-sdk/fastmcp-resources-types.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: types -sidebarTitle: types ---- - -# `fastmcp.resources.types` - - -Concrete resource implementations. - -## Classes - -### `TextResource` - - -A resource that reads from a string. - - -**Methods:** - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Read the text content. - - -### `BinaryResource` - - -A resource that reads from bytes. - - -**Methods:** - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Read the binary content. - - -### `FileResource` - - -A resource that reads from a file. - -Set is_binary=True to read file as binary data instead of text. - - -**Methods:** - -#### `validate_absolute_path` - -```python -validate_absolute_path(cls, path: Path) -> Path -``` - -Ensure path is absolute. - - -#### `set_binary_from_mime_type` - -```python -set_binary_from_mime_type(cls, is_binary: bool, info: ValidationInfo) -> bool -``` - -Set is_binary based on mime_type if not explicitly set. - - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Read the file content. - - -### `HttpResource` - - -A resource that reads from an HTTP endpoint. - - -**Methods:** - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Read the HTTP content. - - -### `DirectoryResource` - - -A resource that lists files in a directory. - - -**Methods:** - -#### `validate_absolute_path` - -```python -validate_absolute_path(cls, path: Path) -> Path -``` - -Ensure path is absolute. - - -#### `list_files` - -```python -list_files(self) -> list[Path] -``` - -List files in the directory. - - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Read the directory listing. - diff --git a/docs/python-sdk/fastmcp-resources-__init__.mdx b/docs/python-sdk/fastmcp-resources.mdx similarity index 72% rename from docs/python-sdk/fastmcp-resources-__init__.mdx rename to docs/python-sdk/fastmcp-resources.mdx index cc5fd2786..b5c8f5a31 100644 --- a/docs/python-sdk/fastmcp-resources-__init__.mdx +++ b/docs/python-sdk/fastmcp-resources.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: resources +sidebarTitle: resources --- # `fastmcp.resources` diff --git a/docs/python-sdk/fastmcp-server-app.mdx b/docs/python-sdk/fastmcp-server-app.mdx deleted file mode 100644 index 7f99ecb53..000000000 --- a/docs/python-sdk/fastmcp-server-app.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: app -sidebarTitle: app ---- - -# `fastmcp.server.app` - - -Backward-compatible re-exports from fastmcp.apps.app. - -.. deprecated:: 3.2.0 - Import from ``fastmcp.apps.app`` or ``fastmcp`` instead. - diff --git a/docs/python-sdk/fastmcp-server-apps.mdx b/docs/python-sdk/fastmcp-server-apps.mdx deleted file mode 100644 index df7d64d44..000000000 --- a/docs/python-sdk/fastmcp-server-apps.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: apps -sidebarTitle: apps ---- - -# `fastmcp.server.apps` - - -Backward-compatible re-exports from fastmcp.apps. - -.. deprecated:: 3.2.0 - Import from ``fastmcp.apps`` instead. - diff --git a/docs/python-sdk/fastmcp-server-auth-__init__.mdx b/docs/python-sdk/fastmcp-server-auth-__init__.mdx deleted file mode 100644 index c86f07005..000000000 --- a/docs/python-sdk/fastmcp-server-auth-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.auth` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-server-auth-auth.mdx b/docs/python-sdk/fastmcp-server-auth-auth.mdx deleted file mode 100644 index 8f7954cd9..000000000 --- a/docs/python-sdk/fastmcp-server-auth-auth.mdx +++ /dev/null @@ -1,382 +0,0 @@ ---- -title: auth -sidebarTitle: auth ---- - -# `fastmcp.server.auth.auth` - -## Classes - -### `AccessToken` - - -AccessToken that includes all JWT claims. - - -### `TokenHandler` - - -TokenHandler that returns MCP-compliant error responses. - -This handler addresses two SDK issues: - -1. Error code: The SDK returns `unauthorized_client` for client authentication - failures, but RFC 6749 Section 5.2 requires `invalid_client` with HTTP 401. - This distinction matters for client re-registration behavior. - -2. Status code: The SDK returns HTTP 400 for all token errors including - `invalid_grant` (expired/invalid tokens). However, the MCP spec requires: - "Invalid or expired tokens MUST receive a HTTP 401 response." - -This handler transforms responses to be compliant with both OAuth 2.1 and MCP specs. - - -**Methods:** - -#### `handle` - -```python -handle(self, request: Any) -``` - -Wrap SDK handle() and transform auth error responses. - - -### `PrivateKeyJWTClientAuthenticator` - - -Client authenticator with private_key_jwt support for CIMD clients. - -Extends the SDK's ClientAuthenticator to add support for the `private_key_jwt` -authentication method per RFC 7523. This is required for CIMD (Client ID Metadata -Document) clients that use asymmetric keys for authentication. - -The authenticator: -1. Delegates to SDK for standard methods (client_secret_basic, client_secret_post, none) -2. Adds private_key_jwt handling for CIMD clients -3. Validates JWT assertions against client's JWKS - - -**Methods:** - -#### `authenticate_request` - -```python -authenticate_request(self, request: Request) -> OAuthClientInformationFull -``` - -Authenticate a client from an HTTP request. - -Extends SDK authentication to support private_key_jwt for CIMD clients. -Delegates to SDK for client_secret_basic (Authorization header) and -client_secret_post (form body) authentication. - - -### `AuthProvider` - - -Base class for all FastMCP authentication providers. - -This class provides a unified interface for all authentication providers, -whether they are simple token verifiers or full OAuth authorization servers. -All providers must be able to verify tokens and can optionally provide -custom authentication routes. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token and return access info if valid. - -All auth providers must implement token verification. - -**Args:** -- `token`: The token string to validate - -**Returns:** -- AccessToken object if valid, None if invalid or expired - - -#### `set_mcp_path` - -```python -set_mcp_path(self, mcp_path: str | None) -> None -``` - -Set the MCP endpoint path and compute resource URL. - -This method is called by get_routes() to configure the expected -resource URL before route creation. Subclasses can override to -perform additional initialization that depends on knowing the -MCP endpoint path. - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") - - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get all routes for this authentication provider. - -This includes both well-known discovery routes and operational routes. -Each provider is responsible for creating whatever routes it needs: -- TokenVerifier: typically no routes (default implementation) -- RemoteAuthProvider: protected resource metadata routes -- OAuthProvider: full OAuth authorization server routes -- Custom providers: whatever routes they need - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata, but the -provider does not create the actual MCP endpoint route. - -**Returns:** -- List of all routes for this provider (excluding the MCP endpoint itself) - - -#### `get_well_known_routes` - -```python -get_well_known_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get well-known discovery routes for this authentication provider. - -This is a utility method that filters get_routes() to return only -well-known discovery routes (those starting with /.well-known/). - -Well-known routes provide OAuth metadata and discovery endpoints that -clients use to discover authentication capabilities. These routes should -be mounted at the root level of the application to comply with RFC 8414 -and RFC 9728. - -Common well-known routes: -- /.well-known/oauth-authorization-server (authorization server metadata) -- /.well-known/oauth-protected-resource/* (protected resource metadata) - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to construct path-scoped well-known URLs. - -**Returns:** -- List of well-known discovery routes (typically mounted at root level) - - -#### `get_middleware` - -```python -get_middleware(self) -> list -``` - -Get HTTP application-level middleware for this auth provider. - -**Returns:** -- List of Starlette Middleware instances to apply to the HTTP app - - -### `TokenVerifier` - - -Base class for token verifiers (Resource Servers). - -This class provides token verification capability without OAuth server functionality. -Token verifiers typically don't provide authentication routes by default. - - -**Methods:** - -#### `scopes_supported` - -```python -scopes_supported(self) -> list[str] -``` - -Scopes to advertise in OAuth metadata. - -Defaults to required_scopes. Override in subclasses when the -advertised scopes differ from the validation scopes (e.g., Azure AD -where tokens contain short-form scopes but clients request full URI -scopes). - - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token and return access info if valid. - - -### `RemoteAuthProvider` - - -Authentication provider for resource servers that verify tokens from known authorization servers. - -This provider composes a TokenVerifier with authorization server metadata to create -standardized OAuth 2.0 Protected Resource endpoints (RFC 9728). Perfect for: -- JWT verification with known issuers -- Remote token introspection services -- Any resource server that knows where its tokens come from - -Use this when you have token verification logic and want to advertise -the authorization servers that issue valid tokens. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify token using the configured token verifier. - - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get routes for this provider. - -Creates protected resource metadata routes (RFC 9728). - - -### `MultiAuth` - - -Composes an optional auth server with additional token verifiers. - -Use this when a single server needs to accept tokens from multiple sources. -For example, an OAuth proxy for interactive clients combined with a JWT -verifier for machine-to-machine tokens. - -Token verification tries the server first (if present), then each verifier -in order, returning the first successful result. Routes and OAuth metadata -come from the server; verifiers contribute only token verification. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a token by trying the server, then each verifier in order. - -Each source is tried independently. If a source raises an exception, -it is logged and treated as a non-match so that remaining sources -still get a chance to verify the token. - - -#### `set_mcp_path` - -```python -set_mcp_path(self, mcp_path: str | None) -> None -``` - -Propagate MCP path to the server and all verifiers. - - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Delegate route creation to the server. - - -#### `get_well_known_routes` - -```python -get_well_known_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Delegate well-known route creation to the server. - -This ensures that server-specific well-known route logic (e.g., -OAuthProvider's RFC 8414 path-aware discovery) is preserved. - - -### `OAuthProvider` - - -OAuth Authorization Server provider. - -This class provides full OAuth server functionality including client registration, -authorization flows, token issuance, and token verification. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token and return access info if valid. - -This method implements the TokenVerifier protocol by delegating -to our existing load_access_token method. - -**Args:** -- `token`: The token string to validate - -**Returns:** -- AccessToken object if valid, None if invalid or expired - - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get OAuth authorization server routes and optional protected resource routes. - -This method creates the full set of OAuth routes including: -- Standard OAuth authorization server routes (/.well-known/oauth-authorization-server, /authorize, /token, etc.) -- Optional protected resource routes - -**Returns:** -- List of OAuth routes - - -#### `get_well_known_routes` - -```python -get_well_known_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get well-known discovery routes with RFC 8414 path-aware support. - -Overrides the base implementation to support path-aware authorization -server metadata discovery per RFC 8414. If issuer_url has a path component, -the authorization server metadata route is adjusted to include that path. - -For example, if issuer_url is "http://example.com/api", the discovery -endpoint will be at "/.well-known/oauth-authorization-server/api" instead -of just "/.well-known/oauth-authorization-server". - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") - -**Returns:** -- List of well-known discovery routes - diff --git a/docs/python-sdk/fastmcp-server-auth-authorization.mdx b/docs/python-sdk/fastmcp-server-auth-authorization.mdx deleted file mode 100644 index 7465c43dc..000000000 --- a/docs/python-sdk/fastmcp-server-auth-authorization.mdx +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: authorization -sidebarTitle: authorization ---- - -# `fastmcp.server.auth.authorization` - - -Authorization checks for FastMCP components. - -This module provides callable-based authorization for tools, resources, and prompts. -Auth checks are functions that receive an AuthContext and return True to allow access -or False to deny. - -Auth checks can also raise exceptions: -- AuthorizationError: Propagates with the custom message for explicit denial -- Other exceptions: Masked for security (logged, treated as auth failure) - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth import require_scopes - - mcp = FastMCP() - - @mcp.tool(auth=require_scopes("write")) - def protected_tool(): ... - - @mcp.resource("data://secret", auth=require_scopes("read")) - def secret_data(): ... - - @mcp.prompt(auth=require_scopes("admin")) - def admin_prompt(): ... - ``` - - -## Functions - -### `require_scopes` - -```python -require_scopes(*scopes: str) -> AuthCheck -``` - - -Require specific OAuth scopes. - -Returns an auth check that requires ALL specified scopes to be present -in the token (AND logic). - -**Args:** -- `*scopes`: One or more scope strings that must all be present. - - -### `restrict_tag` - -```python -restrict_tag(tag: str) -> AuthCheck -``` - - -Restrict components with a specific tag to require certain scopes. - -If the component has the specified tag, the token must have ALL the -required scopes. If the component doesn't have the tag, access is allowed. - -**Args:** -- `tag`: The tag that triggers the scope requirement. -- `scopes`: List of scopes required when the tag is present. - - -### `run_auth_checks` - -```python -run_auth_checks(checks: AuthCheck | list[AuthCheck], ctx: AuthContext) -> bool -``` - - -Run auth checks with AND logic. - -All checks must pass for authorization to succeed. Checks can be -synchronous or asynchronous functions. - -Auth checks can: -- Return True to allow access -- Return False to deny access -- Raise AuthorizationError to deny with a custom message (propagates) -- Raise other exceptions (masked for security, treated as denial) - -**Args:** -- `checks`: A single check function or list of check functions. -Each check can be sync (returns bool) or async (returns Awaitable[bool]). -- `ctx`: The auth context to pass to each check. - -**Returns:** -- True if all checks pass, False if any check fails. - -**Raises:** -- `AuthorizationError`: If an auth check explicitly raises it. - - -## Classes - -### `AuthContext` - - -Context passed to auth check callables. - -This object is passed to each auth check function and provides -access to the current authentication token and the component being accessed. - -**Attributes:** -- `token`: The current access token, or None if unauthenticated. -- `component`: The component (tool, resource, or prompt) being accessed. -- `tool`: Backwards-compatible alias for component when it's a Tool. - - -**Methods:** - -#### `tool` - -```python -tool(self) -> Tool | None -``` - -Backwards-compatible access to the component as a Tool. - -Returns the component if it's a Tool, None otherwise. - diff --git a/docs/python-sdk/fastmcp-server-auth-cimd.mdx b/docs/python-sdk/fastmcp-server-auth-cimd.mdx deleted file mode 100644 index 7cb0dabdc..000000000 --- a/docs/python-sdk/fastmcp-server-auth-cimd.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: cimd -sidebarTitle: cimd ---- - -# `fastmcp.server.auth.cimd` - - -CIMD (Client ID Metadata Document) support for FastMCP. - -.. warning:: - **Beta Feature**: CIMD support is currently in beta. The API may change - in future releases. Please report any issues you encounter. - -CIMD is a simpler alternative to Dynamic Client Registration where clients -host a static JSON document at an HTTPS URL, and that URL becomes their -client_id. See the IETF draft: draft-parecki-oauth-client-id-metadata-document - -This module provides: -- CIMDDocument: Pydantic model for CIMD document validation -- CIMDFetcher: Fetch and validate CIMD documents with SSRF protection -- CIMDClientManager: Manages CIMD client operations - - -## Classes - -### `CIMDDocument` - - -CIMD document per draft-parecki-oauth-client-id-metadata-document. - -The client metadata document is a JSON document containing OAuth client -metadata. The client_id property MUST match the URL where this document -is hosted. - -Key constraint: token_endpoint_auth_method MUST NOT use shared secrets -(client_secret_post, client_secret_basic, client_secret_jwt). - -redirect_uris is required and must contain at least one entry. - - -**Methods:** - -#### `validate_auth_method` - -```python -validate_auth_method(cls, v: str) -> str -``` - -Ensure no shared-secret auth methods are used. - - -#### `validate_redirect_uris` - -```python -validate_redirect_uris(cls, v: list[str]) -> list[str] -``` - -Ensure redirect_uris is non-empty and each entry is a valid URI. - - -### `CIMDValidationError` - - -Raised when CIMD document validation fails. - - -### `CIMDFetchError` - - -Raised when CIMD document fetching fails. - - -### `CIMDFetcher` - - -Fetch and validate CIMD documents with SSRF protection. - -Delegates HTTP fetching to ssrf_safe_fetch_response, which provides DNS -pinning, IP validation, size limits, and timeout enforcement. Documents are -cached using HTTP caching semantics (Cache-Control/ETag/Last-Modified), with -a TTL fallback when response headers do not define caching behavior. - - -**Methods:** - -#### `is_cimd_client_id` - -```python -is_cimd_client_id(self, client_id: str) -> bool -``` - -Check if a client_id looks like a CIMD URL. - -CIMD URLs must be HTTPS with a host and non-root path. - - -#### `fetch` - -```python -fetch(self, client_id_url: str) -> CIMDDocument -``` - -Fetch and validate a CIMD document with SSRF protection. - -Uses ssrf_safe_fetch_response for the HTTP layer, which provides: -- HTTPS only, DNS resolution with IP validation -- DNS pinning (connects to validated IP directly) -- Blocks private/loopback/link-local/multicast IPs -- Response size limit and timeout enforcement -- Redirects disabled - -**Args:** -- `client_id_url`: The URL to fetch (also the expected client_id) - -**Returns:** -- Validated CIMDDocument - -**Raises:** -- `CIMDValidationError`: If document is invalid or URL blocked -- `CIMDFetchError`: If document cannot be fetched - - -#### `validate_redirect_uri` - -```python -validate_redirect_uri(self, doc: CIMDDocument, redirect_uri: str) -> bool -``` - -Validate that a redirect_uri is allowed by the CIMD document. - -Uses component-level matching (scheme, host, port, path) which correctly -handles RFC 8252 §7.3 loopback port flexibility and wildcard patterns. - -**Args:** -- `doc`: The CIMD document -- `redirect_uri`: The redirect URI to validate - -**Returns:** -- True if valid, False otherwise - - -### `CIMDAssertionValidator` - - -Validates JWT assertions for private_key_jwt CIMD clients. - -Implements RFC 7523 (JSON Web Token (JWT) Profile for OAuth 2.0 Client -Authentication and Authorization Grants) for CIMD client authentication. - -JTI replay protection uses TTL-based caching to ensure proper security: -- JTIs are cached with expiration matching the JWT's exp claim -- Expired JTIs are automatically cleaned up -- Maximum assertion lifetime is enforced (5 minutes) - - -**Methods:** - -#### `validate_assertion` - -```python -validate_assertion(self, assertion: str, client_id: str, token_endpoint: str, cimd_doc: CIMDDocument) -> bool -``` - -Validate JWT assertion from client. - -**Args:** -- `assertion`: The JWT assertion string -- `client_id`: Expected client_id (must match iss and sub claims) -- `token_endpoint`: Token endpoint URL (must match aud claim) -- `cimd_doc`: CIMD document containing JWKS for key verification - -**Returns:** -- True if valid - -**Raises:** -- `ValueError`: If validation fails - - -### `CIMDClientManager` - - -Manages all CIMD client operations for OAuth proxy. - -This class encapsulates: -- CIMD client detection -- Document fetching and validation -- Synthetic OAuth client creation -- Private key JWT assertion validation - -This allows the OAuth proxy to delegate all CIMD-specific logic to a -single, focused manager class. - - -**Methods:** - -#### `is_cimd_client_id` - -```python -is_cimd_client_id(self, client_id: str) -> bool -``` - -Check if client_id is a CIMD URL. - -**Args:** -- `client_id`: Client ID to check - -**Returns:** -- True if client_id is an HTTPS URL (CIMD format) - - -#### `get_client` - -```python -get_client(self, client_id_url: str) -``` - -Fetch CIMD document and create synthetic OAuth client. - -**Args:** -- `client_id_url`: HTTPS URL pointing to CIMD document - -**Returns:** -- OAuthProxyClient with CIMD document attached, or None if fetch fails - - -#### `validate_private_key_jwt` - -```python -validate_private_key_jwt(self, assertion: str, client, token_endpoint: str) -> bool -``` - -Validate JWT assertion for private_key_jwt auth. - -**Args:** -- `assertion`: JWT assertion string from client -- `client`: OAuth proxy client (must have cimd_document) -- `token_endpoint`: Token endpoint URL for aud validation - -**Returns:** -- True if assertion is valid - -**Raises:** -- `ValueError`: If client doesn't have CIMD document or validation fails - diff --git a/docs/python-sdk/fastmcp-server-auth-handlers-__init__.mdx b/docs/python-sdk/fastmcp-server-auth-handlers-__init__.mdx deleted file mode 100644 index 7593775fb..000000000 --- a/docs/python-sdk/fastmcp-server-auth-handlers-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.auth.handlers` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-server-auth-handlers-authorize.mdx b/docs/python-sdk/fastmcp-server-auth-handlers-authorize.mdx deleted file mode 100644 index f3f583027..000000000 --- a/docs/python-sdk/fastmcp-server-auth-handlers-authorize.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: authorize -sidebarTitle: authorize ---- - -# `fastmcp.server.auth.handlers.authorize` - - -Enhanced authorization handler with improved error responses. - -This module provides an enhanced authorization handler that wraps the MCP SDK's -AuthorizationHandler to provide better error messages when clients attempt to -authorize with unregistered client IDs. - -The enhancement adds: -- Content negotiation: HTML for browsers, JSON for API clients -- Enhanced JSON responses with registration endpoint hints -- Styled HTML error pages with registration links/forms -- Link headers pointing to registration endpoints - - -## Functions - -### `create_unregistered_client_html` - -```python -create_unregistered_client_html(client_id: str, registration_endpoint: str, discovery_endpoint: str, server_name: str | None = None, server_icon_url: str | None = None, title: str = 'Client Not Registered') -> str -``` - - -Create styled HTML error page for unregistered client attempts. - -**Args:** -- `client_id`: The unregistered client ID that was provided -- `registration_endpoint`: URL of the registration endpoint -- `discovery_endpoint`: URL of the OAuth metadata discovery endpoint -- `server_name`: Optional server name for branding -- `server_icon_url`: Optional server icon URL -- `title`: Page title - -**Returns:** -- HTML string for the error page - - -## Classes - -### `AuthorizationHandler` - - -Authorization handler with enhanced error responses for unregistered clients. - -This handler extends the MCP SDK's AuthorizationHandler to provide better UX -when clients attempt to authorize without being registered. It implements -content negotiation to return: - -- HTML error pages for browser requests -- Enhanced JSON with registration hints for API clients -- Link headers pointing to registration endpoints - -This maintains OAuth 2.1 compliance (returns 400 for invalid client_id) -while providing actionable guidance to fix the error. - - -**Methods:** - -#### `handle` - -```python -handle(self, request: Request) -> Response -``` - -Handle authorization request with enhanced error responses. - -This method extends the SDK's authorization handler and intercepts -errors for unregistered clients to provide better error responses -based on the client's Accept header. - -**Args:** -- `request`: The authorization request - -**Returns:** -- Response (redirect on success, error response on failure) - diff --git a/docs/python-sdk/fastmcp-server-auth-jwt_issuer.mdx b/docs/python-sdk/fastmcp-server-auth-jwt_issuer.mdx deleted file mode 100644 index 9ca0d77ad..000000000 --- a/docs/python-sdk/fastmcp-server-auth-jwt_issuer.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: jwt_issuer -sidebarTitle: jwt_issuer ---- - -# `fastmcp.server.auth.jwt_issuer` - - -JWT token issuance and verification for FastMCP OAuth Proxy. - -This module implements the token factory pattern for OAuth proxies, where the proxy -issues its own JWT tokens to clients instead of forwarding upstream provider tokens. -This maintains proper OAuth 2.0 token audience boundaries. - - -## Functions - -### `derive_jwt_key` - -```python -derive_jwt_key() -> bytes -``` - - -Derive JWT signing key from a high-entropy or low-entropy key material and server salt. - - -## Classes - -### `JWTIssuer` - - -Issues and validates FastMCP-signed JWT tokens using HS256. - -This issuer creates JWT tokens for MCP clients with proper audience claims, -maintaining OAuth 2.0 token boundaries. Tokens are signed with HS256 using -a key derived from the upstream client secret. - - -**Methods:** - -#### `issue_access_token` - -```python -issue_access_token(self, client_id: str, scopes: list[str], jti: str, expires_in: int = 3600, upstream_claims: dict[str, Any] | None = None) -> str -``` - -Issue a minimal FastMCP access token. - -FastMCP tokens are reference tokens containing only the minimal claims -needed for validation and lookup. The JTI maps to the upstream token -which contains actual user identity and authorization data. - -**Args:** -- `client_id`: MCP client ID -- `scopes`: Token scopes -- `jti`: Unique token identifier (maps to upstream token) -- `expires_in`: Token lifetime in seconds -- `upstream_claims`: Optional claims from upstream IdP token to include - -**Returns:** -- Signed JWT token - - -#### `issue_refresh_token` - -```python -issue_refresh_token(self, client_id: str, scopes: list[str], jti: str, expires_in: int, upstream_claims: dict[str, Any] | None = None) -> str -``` - -Issue a minimal FastMCP refresh token. - -FastMCP refresh tokens are reference tokens containing only the minimal -claims needed for validation and lookup. The JTI maps to the upstream -token which contains actual user identity and authorization data. - -**Args:** -- `client_id`: MCP client ID -- `scopes`: Token scopes -- `jti`: Unique token identifier (maps to upstream token) -- `expires_in`: Token lifetime in seconds (should match upstream refresh expiry) -- `upstream_claims`: Optional claims from upstream IdP token to include - -**Returns:** -- Signed JWT token - - -#### `verify_token` - -```python -verify_token(self, token: str, expected_token_use: str = 'access') -> dict[str, Any] -``` - -Verify and decode a FastMCP token. - -Validates JWT signature, expiration, issuer, audience, and token type. - -**Args:** -- `token`: JWT token to verify -- `expected_token_use`: Expected token type ("access" or "refresh"). -Defaults to "access", which rejects refresh tokens. - -**Returns:** -- Decoded token payload - -**Raises:** -- `JoseError`: If token is invalid, expired, or has wrong claims - diff --git a/docs/python-sdk/fastmcp-server-auth-middleware.mdx b/docs/python-sdk/fastmcp-server-auth-middleware.mdx deleted file mode 100644 index 29217a9fe..000000000 --- a/docs/python-sdk/fastmcp-server-auth-middleware.mdx +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: middleware -sidebarTitle: middleware ---- - -# `fastmcp.server.auth.middleware` - - -Enhanced authentication middleware with better error messages. - -This module provides enhanced versions of MCP SDK authentication middleware -that return more helpful error messages for developers troubleshooting -authentication issues. - - -## Classes - -### `RequireAuthMiddleware` - - -Enhanced authentication middleware with detailed error messages. - -Extends the SDK's RequireAuthMiddleware to provide more actionable -error messages when authentication fails. This helps developers -understand what went wrong and how to fix it. - diff --git a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-__init__.mdx b/docs/python-sdk/fastmcp-server-auth-oauth_proxy-__init__.mdx deleted file mode 100644 index 7c4665aa8..000000000 --- a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-__init__.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.auth.oauth_proxy` - - -OAuth Proxy Provider for FastMCP. - -This package provides OAuth proxy functionality split across multiple modules: -- models: Pydantic models and constants -- ui: HTML generation functions -- consent: Consent management mixin -- proxy: Main OAuthProxy class - diff --git a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-consent.mdx b/docs/python-sdk/fastmcp-server-auth-oauth_proxy-consent.mdx deleted file mode 100644 index 72549626d..000000000 --- a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-consent.mdx +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: consent -sidebarTitle: consent ---- - -# `fastmcp.server.auth.oauth_proxy.consent` - - -OAuth Proxy Consent Management. - -This module contains consent management functionality for the OAuth proxy. -The ConsentMixin class provides methods for handling user consent flows, -cookie management, and consent page rendering. - - -## Classes - -### `ConsentMixin` - - -Mixin class providing consent management functionality for OAuthProxy. - -This mixin contains all methods related to: -- Cookie signing and verification -- Consent page rendering -- Consent approval/denial handling -- URI normalization for consent tracking - diff --git a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-models.mdx b/docs/python-sdk/fastmcp-server-auth-oauth_proxy-models.mdx deleted file mode 100644 index df32a5b2b..000000000 --- a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-models.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: models -sidebarTitle: models ---- - -# `fastmcp.server.auth.oauth_proxy.models` - - -OAuth Proxy Models and Constants. - -This module contains all Pydantic models and constants used by the OAuth proxy. - - -## Classes - -### `OAuthTransaction` - - -OAuth transaction state for consent flow. - -Stored server-side to track active authorization flows with client context. -Includes CSRF tokens for consent protection per MCP security best practices. - - -### `ClientCode` - - -Client authorization code with PKCE and upstream tokens. - -Stored server-side after upstream IdP callback. Contains the upstream -tokens bound to the client's PKCE challenge for secure token exchange. - - -### `UpstreamTokenSet` - - -Stored upstream OAuth tokens from identity provider. - -These tokens are obtained from the upstream provider (Google, GitHub, etc.) -and stored in plaintext within this model. Encryption is handled transparently -at the storage layer via FernetEncryptionWrapper. Tokens are never exposed to MCP clients. - - -### `JTIMapping` - - -Maps FastMCP token JTI to upstream token ID. - -This allows stateless JWT validation while still being able to look up -the corresponding upstream token when tools need to access upstream APIs. - - -### `RefreshTokenMetadata` - - -Metadata for a refresh token, stored keyed by token hash. - -We store only metadata (not the token itself) for security - if storage -is compromised, attackers get hashes they can't reverse into usable tokens. - - -### `ProxyDCRClient` - - -Client for DCR proxy with configurable redirect URI validation. - -This special client class is critical for the OAuth proxy to work correctly -with Dynamic Client Registration (DCR). Here's why it exists: - -Problem: --------- -When MCP clients use OAuth, they dynamically register with random localhost -ports (e.g., http://localhost:55454/callback). The OAuth proxy needs to: -1. Accept these dynamic redirect URIs from clients based on configured patterns -2. Use its own fixed redirect URI with the upstream provider (Google, GitHub, etc.) -3. Forward the authorization code back to the client's dynamic URI - -Solution: ---------- -This class validates redirect URIs against configurable patterns, -while the proxy internally uses its own fixed redirect URI with the upstream -provider. This allows the flow to work even when clients reconnect with -different ports or when tokens are cached. - -Without proper validation, clients could get "Redirect URI not registered" errors -when trying to authenticate with cached tokens, or security vulnerabilities could -arise from accepting arbitrary redirect URIs. - - -**Methods:** - -#### `validate_redirect_uri` - -```python -validate_redirect_uri(self, redirect_uri: AnyUrl | None) -> AnyUrl -``` - -Validate redirect URI against proxy patterns and optionally CIMD redirect_uris. - -For CIMD clients: validates against BOTH the CIMD document's redirect_uris -AND the proxy's allowed patterns (if configured). Both must pass. - -For DCR clients: validates against proxy patterns first, falling back to -base validation (registered redirect_uris) if patterns don't match. - diff --git a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-proxy.mdx b/docs/python-sdk/fastmcp-server-auth-oauth_proxy-proxy.mdx deleted file mode 100644 index 887622070..000000000 --- a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-proxy.mdx +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: proxy -sidebarTitle: proxy ---- - -# `fastmcp.server.auth.oauth_proxy.proxy` - - -OAuth Proxy Provider for FastMCP. - -This provider acts as a transparent proxy to an upstream OAuth Authorization Server, -handling Dynamic Client Registration locally while forwarding all other OAuth flows. -This enables authentication with upstream providers that don't support DCR or have -restricted client registration policies. - -Key features: -- Proxies authorization and token endpoints to upstream server -- Implements local Dynamic Client Registration with fixed upstream credentials -- Validates tokens using upstream JWKS -- Maintains minimal local state for bookkeeping -- Enhanced logging with request correlation - -This implementation is based on the OAuth 2.1 specification and is designed for -production use with enterprise identity providers. - - -## Classes - -### `OAuthProxy` - - -OAuth provider that presents a DCR-compliant interface while proxying to non-DCR IDPs. - -Purpose -------- -MCP clients expect OAuth providers to support Dynamic Client Registration (DCR), -where clients can register themselves dynamically and receive unique credentials. -Most enterprise IDPs (Google, GitHub, Azure AD, etc.) don't support DCR and require -pre-registered OAuth applications with fixed credentials. - -This proxy bridges that gap by: -- Presenting a full DCR-compliant OAuth interface to MCP clients -- Translating DCR registration requests to use pre-configured upstream credentials -- Proxying all OAuth flows to the upstream IDP with appropriate translations -- Managing the state and security requirements of both protocols - -Architecture Overview --------------------- -The proxy maintains a single OAuth app registration with the upstream provider -while allowing unlimited MCP clients to register and authenticate dynamically. -It implements the complete OAuth 2.1 + DCR specification for clients while -translating to whatever OAuth variant the upstream provider requires. - -Key Translation Challenges Solved ---------------------------------- -1. Dynamic Client Registration: - - MCP clients expect to register dynamically and get unique credentials - - Upstream IDPs require pre-registered apps with fixed credentials - - Solution: Accept DCR requests, return shared upstream credentials - -2. Dynamic Redirect URIs: - - MCP clients use random localhost ports that change between sessions - - Upstream IDPs require fixed, pre-registered redirect URIs - - Solution: Use proxy's fixed callback URL with upstream, forward to client's dynamic URI - -3. Authorization Code Mapping: - - Upstream returns codes for the proxy's redirect URI - - Clients expect codes for their own redirect URIs - - Solution: Exchange upstream code server-side, issue new code to client - -4. State Parameter Collision: - - Both client and proxy need to maintain state through the flow - - Only one state parameter available in OAuth - - Solution: Use transaction ID as state with upstream, preserve client's state - -5. Token Management: - - Clients may expect different token formats/claims than upstream provides - - Need to track tokens for revocation and refresh - - Solution: Store token relationships, forward upstream tokens transparently - -OAuth Flow Implementation ------------------------- -1. Client Registration (DCR): - - Accept any client registration request - - Store ProxyDCRClient that accepts dynamic redirect URIs - -2. Authorization: - - Store transaction mapping client details to proxy flow - - Redirect to upstream with proxy's fixed redirect URI - - Use transaction ID as state parameter with upstream - -3. Upstream Callback: - - Exchange upstream authorization code for tokens (server-side) - - Generate new authorization code bound to client's PKCE challenge - - Redirect to client's original dynamic redirect URI - -4. Token Exchange: - - Validate client's code and PKCE verifier - - Return previously obtained upstream tokens - - Clean up one-time use authorization code - -5. Token Refresh: - - Forward refresh requests to upstream using authlib - - Handle token rotation if upstream issues new refresh token - - Update local token mappings - -State Management ---------------- -The proxy maintains minimal but crucial state via pluggable storage (client_storage): -- _oauth_transactions: Active authorization flows with client context -- _client_codes: Authorization codes with PKCE challenges and upstream tokens -- _jti_mapping_store: Maps FastMCP token JTIs to upstream token IDs -- _refresh_token_store: Refresh token metadata (keyed by token hash) - -All state is stored in the configured client_storage backend (Redis, disk, etc.) -enabling horizontal scaling across multiple instances. - -Security Considerations ----------------------- -- Refresh tokens stored by hash only (defense in depth if storage compromised) -- PKCE enforced end-to-end (client to proxy, proxy to upstream) -- Authorization codes are single-use with short expiry -- Transaction IDs are cryptographically random -- All state is cleaned up after use to prevent replay -- Token validation delegates to upstream provider - -Provider Compatibility ---------------------- -Works with any OAuth 2.0 provider that supports: -- Authorization code flow -- Fixed redirect URI (configured in provider's app settings) -- Standard token endpoint - -Handles provider-specific requirements: -- Google: Ensures minimum scope requirements -- GitHub: Compatible with OAuth Apps and GitHub Apps -- Azure AD: Handles tenant-specific endpoints -- Generic: Works with any spec-compliant provider - - -**Methods:** - -#### `set_mcp_path` - -```python -set_mcp_path(self, mcp_path: str | None) -> None -``` - -Set the MCP endpoint path and create JWTIssuer with correct audience. - -This method is called by get_routes() to configure the resource URL -and create the JWTIssuer. The JWT audience is set to the full resource -URL (e.g., http://localhost:8000/mcp) to ensure tokens are bound to -this specific MCP endpoint. - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") - - -#### `jwt_issuer` - -```python -jwt_issuer(self) -> JWTIssuer -``` - -Get the JWT issuer, ensuring it has been initialized. - -The JWT issuer is created when set_mcp_path() is called (via get_routes()). -This property ensures a clear error if used before initialization. - - -#### `get_client` - -```python -get_client(self, client_id: str) -> OAuthClientInformationFull | None -``` - -Get client information by ID. This is generally the random ID -provided to the DCR client during registration, not the upstream client ID. - -For unregistered clients, returns None (which will raise an error in the SDK). -CIMD clients (URL-based client IDs) are looked up and cached automatically. - - -#### `register_client` - -```python -register_client(self, client_info: OAuthClientInformationFull) -> None -``` - -Register a client locally - -When a client registers, we create a ProxyDCRClient that is more -forgiving about validating redirect URIs, since the DCR client's -redirect URI will likely be localhost or unknown to the proxied IDP. The -proxied IDP only knows about this server's fixed redirect URI. - - -#### `authorize` - -```python -authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str -``` - -Start OAuth transaction and route through consent interstitial. - -Flow: -1. Validate client's resource matches server's resource URL (security check) -2. Store transaction with client details and PKCE (if forwarding) -3. Return local /consent URL; browser visits consent first -4. Consent handler redirects to upstream IdP if approved/already approved - -If consent is disabled (require_authorization_consent=False or "external"), -skip the consent screen and redirect directly to the upstream IdP. In -"remember" mode, still route through /consent so the cookie lookup and -Sec-Fetch-Site gating can run. - - -#### `load_authorization_code` - -```python -load_authorization_code(self, client: OAuthClientInformationFull, authorization_code: str) -> AuthorizationCode | None -``` - -Load authorization code for validation. - -Look up our client code and return authorization code object -with PKCE challenge for validation. - - -#### `exchange_authorization_code` - -```python -exchange_authorization_code(self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode) -> OAuthToken -``` - -Exchange authorization code for FastMCP-issued tokens. - -Implements the token factory pattern: -1. Retrieves upstream tokens from stored authorization code -2. Extracts user identity from upstream token -3. Encrypts and stores upstream tokens -4. Issues FastMCP-signed JWT tokens -5. Returns FastMCP tokens (NOT upstream tokens) - -PKCE validation is handled by the MCP framework before this method is called. - - -#### `load_refresh_token` - -```python -load_refresh_token(self, client: OAuthClientInformationFull, refresh_token: str) -> RefreshToken | None -``` - -Load refresh token metadata from distributed storage. - -Looks up by token hash and reconstructs the RefreshToken object. -Validates that the token belongs to the requesting client. - - -#### `exchange_refresh_token` - -```python -exchange_refresh_token(self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken -``` - -Exchange FastMCP refresh token for new FastMCP access token. - -Implements two-tier refresh: -1. Verify FastMCP refresh token -2. Look up upstream token via JTI mapping -3. Refresh upstream token with upstream provider -4. Update stored upstream token -5. Issue new FastMCP access token -6. Keep same FastMCP refresh token (unless upstream rotates) - - -#### `load_access_token` - -```python -load_access_token(self, token: str) -> AccessToken | None -``` - -Validate FastMCP JWT by swapping for upstream token. - -This implements the token swap pattern: -1. Verify FastMCP JWT signature (proves it's our token) -2. Look up upstream token via JTI mapping -3. Decrypt upstream token -4. Validate upstream token with provider (GitHub API, JWT validation, etc.) -5. If upstream validation fails, attempt transparent refresh -6. Return upstream validation result - -The FastMCP JWT is a reference token - all authorization data comes -from validating the upstream token via the TokenVerifier. - - -#### `revoke_token` - -```python -revoke_token(self, token: AccessToken | RefreshToken) -> None -``` - -Revoke token locally and with upstream server if supported. - -For refresh tokens, removes from local storage by hash. -For all tokens, attempts upstream revocation if endpoint is configured. -Access token JTI mappings expire via TTL. - - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get OAuth routes with custom handlers for better error UX. - -This method creates standard OAuth routes and replaces: -- /authorize endpoint: Enhanced error responses for unregistered clients -- /token endpoint: OAuth 2.1 compliant error codes - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata. - diff --git a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-ui.mdx b/docs/python-sdk/fastmcp-server-auth-oauth_proxy-ui.mdx deleted file mode 100644 index fdbd2eb50..000000000 --- a/docs/python-sdk/fastmcp-server-auth-oauth_proxy-ui.mdx +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: ui -sidebarTitle: ui ---- - -# `fastmcp.server.auth.oauth_proxy.ui` - - -OAuth Proxy UI Generation Functions. - -This module contains HTML generation functions for consent and error pages. - - -## Functions - -### `create_consent_html` - -```python -create_consent_html(client_id: str, redirect_uri: str, scopes: list[str], txn_id: str, csrf_token: str, client_name: str | None = None, title: str = 'Application Access Request', server_name: str | None = None, server_icon_url: str | None = None, server_website_url: str | None = None, client_website_url: str | None = None, csp_policy: str | None = None, is_cimd_client: bool = False, cimd_domain: str | None = None) -> str -``` - - -Create a styled HTML consent page for OAuth authorization requests. - -**Args:** -- `csp_policy`: Content Security Policy override. -If None, uses the built-in CSP policy with appropriate directives. -If empty string "", disables CSP entirely (no meta tag is rendered). -If a non-empty string, uses that as the CSP policy value. - - -### `create_error_html` - -```python -create_error_html(error_title: str, error_message: str, error_details: dict[str, str] | None = None, server_name: str | None = None, server_icon_url: str | None = None) -> str -``` - - -Create a styled HTML error page for OAuth errors. - -**Args:** -- `error_title`: The error title (e.g., "OAuth Error", "Authorization Failed") -- `error_message`: The main error message to display -- `error_details`: Optional dictionary of error details to show (e.g., `{"Error Code"\: "invalid_client"}`) -- `server_name`: Optional server name to display -- `server_icon_url`: Optional URL to server icon/logo - -**Returns:** -- Complete HTML page as a string - diff --git a/docs/python-sdk/fastmcp-server-auth-oidc_proxy.mdx b/docs/python-sdk/fastmcp-server-auth-oidc_proxy.mdx deleted file mode 100644 index 3bcbc3cb2..000000000 --- a/docs/python-sdk/fastmcp-server-auth-oidc_proxy.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: oidc_proxy -sidebarTitle: oidc_proxy ---- - -# `fastmcp.server.auth.oidc_proxy` - - -OIDC Proxy Provider for FastMCP. - -This provider acts as a transparent proxy to an upstream OIDC compliant Authorization -Server. It leverages the OAuthProxy class to handle Dynamic Client Registration and -forwarding of all OAuth flows. - -This implementation is based on: - OpenID Connect Discovery 1.0 - https://openid.net/specs/openid-connect-discovery-1_0.html - OAuth 2.0 Authorization Server Metadata - https://datatracker.ietf.org/doc/html/rfc8414 - - -## Classes - -### `OIDCConfiguration` - - -OIDC Configuration. - - -**Methods:** - -#### `get_oidc_configuration` - -```python -get_oidc_configuration(cls, config_url: AnyHttpUrl) -> Self -``` - -Get the OIDC configuration for the specified config URL. - -**Args:** -- `config_url`: The OIDC config URL -- `strict`: The strict flag for the configuration -- `timeout_seconds`: HTTP request timeout in seconds - - -### `OIDCProxy` - - -OAuth provider that wraps OAuthProxy to provide configuration via an OIDC configuration URL. - -This provider makes it easier to add OAuth protection for any upstream provider -that is OIDC compliant. - - -**Methods:** - -#### `get_oidc_configuration` - -```python -get_oidc_configuration(self, config_url: AnyHttpUrl, strict: bool | None, timeout_seconds: int | None) -> OIDCConfiguration -``` - -Gets the OIDC configuration for the specified configuration URL. - -**Args:** -- `config_url`: The OIDC configuration URL -- `strict`: The strict flag for the configuration -- `timeout_seconds`: HTTP request timeout in seconds - - -#### `get_token_verifier` - -```python -get_token_verifier(self) -> TokenVerifier -``` - -Creates the token verifier for the specified OIDC configuration and arguments. - -**Args:** -- `algorithm`: Optional token verifier algorithm -- `audience`: Optional token verifier audience -- `required_scopes`: Optional token verifier required_scopes -- `timeout_seconds`: HTTP request timeout in seconds - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-__init__.mdx b/docs/python-sdk/fastmcp-server-auth-providers-__init__.mdx deleted file mode 100644 index 9de7cce8a..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.auth.providers` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-server-auth-providers-auth0.mdx b/docs/python-sdk/fastmcp-server-auth-providers-auth0.mdx deleted file mode 100644 index 350d3f2e6..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-auth0.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: auth0 -sidebarTitle: auth0 ---- - -# `fastmcp.server.auth.providers.auth0` - - -Auth0 OAuth provider for FastMCP. - -This module provides a complete Auth0 integration that's ready to use with -just the configuration URL, client ID, client secret, audience, and base URL. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.auth0 import Auth0Provider - - # Simple Auth0 OAuth protection - auth = Auth0Provider( - config_url="https://auth0.config.url", - client_id="your-auth0-client-id", - client_secret="your-auth0-client-secret", - audience="your-auth0-api-audience", - base_url="http://localhost:8000", - ) - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `Auth0Provider` - - -An Auth0 provider implementation for FastMCP. - -This provider is a complete Auth0 integration that's ready to use with -just the configuration URL, client ID, client secret, audience, and base URL. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-aws.mdx b/docs/python-sdk/fastmcp-server-auth-providers-aws.mdx deleted file mode 100644 index d3201311e..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-aws.mdx +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: aws -sidebarTitle: aws ---- - -# `fastmcp.server.auth.providers.aws` - - -AWS Cognito OAuth provider for FastMCP. - -This module provides a complete AWS Cognito OAuth integration that's ready to use -with a user pool ID, domain prefix, client ID and client secret. It handles all -the complexity of AWS Cognito's OAuth flow, token validation, and user management. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.aws_cognito import AWSCognitoProvider - - # Simple AWS Cognito OAuth protection - auth = AWSCognitoProvider( - user_pool_id="your-user-pool-id", - aws_region="eu-central-1", - client_id="your-cognito-client-id", - client_secret="your-cognito-client-secret" - ) - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `AWSCognitoTokenVerifier` - - -Token verifier for Cognito access tokens. - -Cognito access tokens use a ``client_id`` claim instead of the -standard ``aud`` claim. This subclass passes ``audience=None`` -to the parent (skipping the ``aud`` check) and validates the -``client_id`` claim directly. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify token and filter claims to Cognito-specific subset. - - -### `AWSCognitoProvider` - - -Complete AWS Cognito OAuth provider for FastMCP. - -This provider makes it trivial to add AWS Cognito OAuth protection to any -FastMCP server using OIDC Discovery. Just provide your Cognito User Pool details, -client credentials, and a base URL, and you're ready to go. - -Features: -- Automatic OIDC Discovery from AWS Cognito User Pool -- Automatic JWT token validation via Cognito's public keys -- Cognito-specific claim filtering (sub, username, cognito:groups) -- Support for Cognito User Pools - - -**Methods:** - -#### `get_token_verifier` - -```python -get_token_verifier(self) -> AWSCognitoTokenVerifier -``` - -Creates a Cognito-specific token verifier with claim filtering. - -**Args:** -- `algorithm`: Optional token verifier algorithm -- `audience`: Optional token verifier audience -- `required_scopes`: Optional token verifier required_scopes -- `timeout_seconds`: HTTP request timeout in seconds - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-azure.mdx b/docs/python-sdk/fastmcp-server-auth-providers-azure.mdx deleted file mode 100644 index 3eaf5fef4..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-azure.mdx +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: azure -sidebarTitle: azure ---- - -# `fastmcp.server.auth.providers.azure` - - -Azure (Microsoft Entra) OAuth provider for FastMCP. - -This provider implements Azure/Microsoft Entra ID OAuth authentication -using the OAuth Proxy pattern for non-DCR OAuth flows. - - -## Functions - -### `EntraOBOToken` - -```python -EntraOBOToken(scopes: list[str]) -> str -``` - - -Exchange the user's Entra token for a downstream API token via OBO. - -This dependency performs a Microsoft Entra On-Behalf-Of (OBO) token exchange, -allowing your MCP server to call downstream APIs (like Microsoft Graph) on -behalf of the authenticated user. - -**Args:** -- `scopes`: The scopes to request for the downstream API. For Microsoft Graph, -use scopes like ["https\://graph.microsoft.com/Mail.Read"] or -["https\://graph.microsoft.com/.default"]. - -**Returns:** -- A dependency that resolves to the downstream API access token string - -**Raises:** -- `ImportError`: If fastmcp[azure] is not installed -- `RuntimeError`: If no access token is available, provider is not Azure, -or OBO exchange fails - - -## Classes - -### `AzureProvider` - - -Azure (Microsoft Entra) OAuth provider for FastMCP. - -This provider implements Azure/Microsoft Entra ID authentication using the -OAuth Proxy pattern. It supports both organizational accounts and personal -Microsoft accounts depending on the tenant configuration. - -Scope Handling: -- required_scopes: Provide unprefixed scope names (e.g., ["read", "write"]) - → Automatically prefixed with identifier_uri during initialization - → Validated on all tokens and advertised to MCP clients -- additional_authorize_scopes: Provide full format (e.g., ["User.Read"]) - → NOT prefixed, NOT validated, NOT advertised to clients - → Used to request Microsoft Graph or other upstream API permissions - -Features: -- OAuth proxy to Azure/Microsoft identity platform -- JWT validation using tenant issuer and JWKS -- Supports tenant configurations: specific tenant ID, "organizations", or "consumers" -- Custom API scopes and Microsoft Graph scopes in a single provider - -Setup: -1. Create an App registration in Azure Portal -2. Configure Web platform redirect URI: http://localhost:8000/auth/callback (or your custom path) -3. Add an Application ID URI under "Expose an API" (defaults to api://{client_id}) -4. Add custom scopes (e.g., "read", "write") under "Expose an API" -5. Set access token version to 2 in the App manifest: "requestedAccessTokenVersion": 2 -6. Create a client secret -7. Get Application (client) ID, Directory (tenant) ID, and client secret - - -**Methods:** - -#### `from_b2c` - -```python -from_b2c(cls, **kwargs: Any) -> AzureProvider -``` - -Create an AzureProvider pre-configured for Azure AD B2C. - -Derives authority host, tenant path, and identifier URI from -`tenant_name` and `policy_name`, then delegates to the standard -constructor. Returns a plain `AzureProvider` instance. - -B2C issuer validation is disabled by default (`token_issuer=None`) -because B2C issuers embed the tenant GUID. Pass an explicit -`token_issuer` string once you know the real `iss` value. - -Azure AD B2C does **not** support OBO. - -**Args:** -- `tenant_name`: Short B2C tenant name without `.onmicrosoft.com` -(e.g. `"mytenant"`). -- `policy_name`: User-flow or custom-policy name -(e.g. `"B2C_1_susi"`). -- `client_id`: Application (client) ID from the B2C app registration. -- `client_secret`: Client secret from the B2C app registration. -- `required_scopes`: Custom API scope names without prefix -(e.g. `["mcp-access"]`). -- `base_url`: Public base URL of this server. -- `custom_domain`: Custom domain for the B2C authority -(e.g. `"auth.mycompany.com"`). Defaults to -`{tenant_name}.b2clogin.com`. -- `identifier_uri`: Application ID URI. Defaults to -`https\://{tenant_name}.onmicrosoft.com/{client_id}`. -- `token_issuer`: Expected `iss` claim. `None` (default) disables -issuer validation. -- `**kwargs`: Forwarded to `AzureProvider.__init__`. - - -#### `authorize` - -```python -authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str -``` - -Start OAuth transaction and redirect to Azure AD. - -Override parent's authorize method to filter out the 'resource' parameter -which is not supported by Azure AD v2.0 endpoints. The v2.0 endpoints use -scopes to determine the resource/audience instead of a separate parameter. - -**Args:** -- `client`: OAuth client information -- `params`: Authorization parameters from the client - -**Returns:** -- Authorization URL to redirect the user to Azure AD - - -#### `get_obo_credential` - -```python -get_obo_credential(self, user_assertion: str) -> OnBehalfOfCredential -``` - -Get a cached or new OnBehalfOfCredential for OBO token exchange. - -Credentials are cached by user assertion so the Azure SDK's internal -token cache can avoid redundant OBO exchanges when the same user -calls multiple tools with the same scopes. - -**Args:** -- `user_assertion`: The user's access token to exchange via OBO. - -**Returns:** -- A configured OnBehalfOfCredential ready for get_token() calls. - -**Raises:** -- `NotImplementedError`: If OBO is not supported (e.g. Azure AD B2C). -- `ImportError`: If azure-identity is not installed (requires fastmcp[azure]). - - -#### `close_obo_credentials` - -```python -close_obo_credentials(self) -> None -``` - -Close all cached OBO credentials. - - -### `AzureJWTVerifier` - - -JWT verifier pre-configured for Azure AD / Microsoft Entra ID. - -Auto-configures JWKS URI, issuer, audience, and scope handling from your -Azure app registration details. Designed for Managed Identity and other -token-verification-only scenarios where AzureProvider's full OAuth proxy -isn't needed. - -Handles Azure's scope format automatically: -- Validates tokens using short-form scopes (what Azure puts in ``scp`` claims) -- Advertises full-URI scopes in OAuth metadata (what clients need to request) - -Example:: - - from fastmcp.server.auth import RemoteAuthProvider - from fastmcp.server.auth.providers.azure import AzureJWTVerifier - from pydantic import AnyHttpUrl - - verifier = AzureJWTVerifier( - client_id="your-client-id", - tenant_id="your-tenant-id", - required_scopes=["access_as_user"], - ) - - auth = RemoteAuthProvider( - token_verifier=verifier, - authorization_servers=[ - AnyHttpUrl("https://login.microsoftonline.com/your-tenant-id/v2.0") - ], - base_url="https://my-server.com", - ) - - -**Methods:** - -#### `scopes_supported` - -```python -scopes_supported(self) -> list[str] -``` - -Return scopes with Azure URI prefix for OAuth metadata. - -Azure tokens contain short-form scopes (e.g., ``read``) in the ``scp`` -claim, but clients must request full URI scopes (e.g., -``api://client-id/read``) from the Azure authorization endpoint. This -property returns the full-URI form for OAuth metadata while -``required_scopes`` retains the short form for token validation. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-clerk.mdx b/docs/python-sdk/fastmcp-server-auth-providers-clerk.mdx deleted file mode 100644 index 5add0fff2..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-clerk.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: clerk -sidebarTitle: clerk ---- - -# `fastmcp.server.auth.providers.clerk` - - -Clerk OAuth provider for FastMCP. - -This module provides a complete Clerk OAuth integration that's ready to use -with a Clerk domain, client ID, and client secret. It handles all the complexity -of Clerk's OAuth/OIDC flow, token validation, and user management. - -Clerk uses standard OIDC endpoints derived from the instance domain -(e.g., ``https://.clerk.accounts.dev``). Token verification is -performed via the introspection endpoint (RFC 7662) for security-critical -checks (active status, audience, scopes), followed by the userinfo endpoint -for profile enrichment. Userinfo failure is non-fatal. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.clerk import ClerkProvider - - auth = ClerkProvider( - domain="saving-primate-16.clerk.accounts.dev", - client_id="your-clerk-client-id", - client_secret="your-clerk-client-secret", - base_url="https://my-server.com", - ) - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `ClerkTokenVerifier` - - -Token verifier for Clerk OAuth tokens. - -Clerk issues standard OIDC tokens. Verification uses the introspection -endpoint (RFC 7662) as the primary security gate — it confirms the token -is active and provides metadata (scopes, expiry, audience). The userinfo -endpoint is called second for profile enrichment (name, email, picture) -and its failure is non-fatal. - -When a ``client_id`` is configured, the audience from introspection is -validated against it. When ``required_scopes`` are configured, -introspection must return the token's scopes — the verifier will not -assume scopes when introspection is unavailable. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a Clerk OAuth token via introspection and userinfo. - -Calls the introspection endpoint first to validate the token and -retrieve auth metadata (active status, scopes, expiry, audience). -If the token passes security checks, the userinfo endpoint is called -for profile enrichment. Userinfo failure is non-fatal. - -When a ``client_id`` is configured, the token's audience must match it. -When ``required_scopes`` are configured, introspection must confirm -them; tokens are rejected if scope information is unavailable. - - -### `ClerkProvider` - - -Complete Clerk OAuth provider for FastMCP. - -This provider makes it trivial to add Clerk OAuth protection to any -FastMCP server. Provide your Clerk instance domain, OAuth app credentials, -and a base URL, and you're ready to go. - -Clerk uses standard OIDC endpoints derived from the instance domain. -All endpoint URLs are constructed automatically from the domain parameter. - -Features: -- Transparent OAuth proxy to Clerk -- Automatic token validation via Clerk's userinfo & introspection APIs -- User information extraction from Clerk's OIDC claims -- PKCE support (S256) -- Minimal configuration required - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-debug.mdx b/docs/python-sdk/fastmcp-server-auth-providers-debug.mdx deleted file mode 100644 index 8ed3e6b87..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-debug.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: debug -sidebarTitle: debug ---- - -# `fastmcp.server.auth.providers.debug` - - -Debug token verifier for testing and special cases. - -This module provides a flexible token verifier that delegates validation -to a custom callable. Useful for testing, development, or scenarios where -standard verification isn't possible (like opaque tokens without introspection). - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.debug import DebugTokenVerifier - - # Accept all tokens (default - useful for testing) - auth = DebugTokenVerifier() - - # Custom sync validation logic - auth = DebugTokenVerifier(validate=lambda token: token.startswith("valid-")) - - # Custom async validation logic - async def check_cache(token: str) -> bool: - return await redis.exists(f"token:{token}") - - auth = DebugTokenVerifier(validate=check_cache) - - mcp = FastMCP("My Server", auth=auth) - ``` - - -## Classes - -### `DebugTokenVerifier` - - -Token verifier with custom validation logic. - -This verifier delegates token validation to a user-provided callable. -By default, it accepts all non-empty tokens (useful for testing). - -Use cases: -- Testing: Accept any token without real verification -- Development: Custom validation logic for prototyping -- Opaque tokens: When you have tokens with no introspection endpoint - -WARNING: This bypasses standard security checks. Only use in controlled -environments or when you understand the security implications. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify token using custom validation logic. - -**Args:** -- `token`: The token string to validate - -**Returns:** -- AccessToken if validation succeeds, None otherwise - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-descope.mdx b/docs/python-sdk/fastmcp-server-auth-providers-descope.mdx deleted file mode 100644 index 45dce934e..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-descope.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: descope -sidebarTitle: descope ---- - -# `fastmcp.server.auth.providers.descope` - - -Descope authentication provider for FastMCP. - -This module provides DescopeProvider - a complete authentication solution that integrates -with Descope's OAuth 2.1 and OpenID Connect services, supporting Dynamic Client Registration (DCR) -for seamless MCP client authentication. - - -## Classes - -### `DescopeProvider` - - -Descope metadata provider for DCR (Dynamic Client Registration). - -This provider implements Descope integration using metadata forwarding. -This is the recommended approach for Descope DCR -as it allows Descope to handle the OAuth flow directly while FastMCP acts -as a resource server. - -IMPORTANT SETUP REQUIREMENTS: - -1. Create an MCP Server in Descope Console: - - Go to the [MCP Servers page](https://app.descope.com/mcp-servers) of the Descope Console - - Create a new MCP Server - - Ensure that **Dynamic Client Registration (DCR)** is enabled - - Note your Well-Known URL - -2. Note your Well-Known URL: - - Save your Well-Known URL from [MCP Server Settings](https://app.descope.com/mcp-servers) - - Format: ``https://.../v1/apps/agentic/P.../M.../.well-known/openid-configuration`` - -For detailed setup instructions, see: -https://docs.descope.com/identity-federation/inbound-apps/creating-inbound-apps#method-2-dynamic-client-registration-dcr - - -**Methods:** - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get OAuth routes including Descope authorization server metadata forwarding. - -This returns the standard protected resource routes plus an authorization server -metadata endpoint that forwards Descope's OAuth metadata to clients. - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-discord.mdx b/docs/python-sdk/fastmcp-server-auth-providers-discord.mdx deleted file mode 100644 index 57d3b743b..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-discord.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: discord -sidebarTitle: discord ---- - -# `fastmcp.server.auth.providers.discord` - - -Discord OAuth provider for FastMCP. - -This module provides a complete Discord OAuth integration that's ready to use -with just a client ID and client secret. It handles all the complexity of -Discord's OAuth flow, token validation, and user management. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.discord import DiscordProvider - - # Simple Discord OAuth protection - auth = DiscordProvider( - client_id="your-discord-client-id", - client_secret="your-discord-client-secret" - ) - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `DiscordTokenVerifier` - - -Token verifier for Discord OAuth tokens. - -Discord OAuth tokens are opaque (not JWTs), so we verify them -by calling Discord's tokeninfo API to check if they're valid and get user info. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify Discord OAuth token by calling Discord's tokeninfo API. - - -### `DiscordProvider` - - -Complete Discord OAuth provider for FastMCP. - -This provider makes it trivial to add Discord OAuth protection to any -FastMCP server. Just provide your Discord OAuth app credentials and -a base URL, and you're ready to go. - -Features: -- Transparent OAuth proxy to Discord -- Automatic token validation via Discord's API -- User information extraction from Discord APIs -- Minimal configuration required - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-github.mdx b/docs/python-sdk/fastmcp-server-auth-providers-github.mdx deleted file mode 100644 index 48d8e24da..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-github.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: github -sidebarTitle: github ---- - -# `fastmcp.server.auth.providers.github` - - -GitHub OAuth provider for FastMCP. - -This module provides a complete GitHub OAuth integration that's ready to use -with just a client ID and client secret. It handles all the complexity of -GitHub's OAuth flow, token validation, and user management. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.github import GitHubProvider - - # Simple GitHub OAuth protection - auth = GitHubProvider( - client_id="your-github-client-id", - client_secret="your-github-client-secret" - ) - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `GitHubTokenVerifier` - - -Token verifier for GitHub OAuth tokens. - -GitHub OAuth tokens are opaque (not JWTs), so we verify them -by calling GitHub's API to check if they're valid and get user info. - -Caching is disabled by default. Set ``cache_ttl_seconds`` to a positive -integer to cache successful verification results and avoid repeated -GitHub API calls for the same token. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify GitHub OAuth token by calling GitHub API. - - -### `GitHubProvider` - - -Complete GitHub OAuth provider for FastMCP. - -This provider makes it trivial to add GitHub OAuth protection to any -FastMCP server. Just provide your GitHub OAuth app credentials and -a base URL, and you're ready to go. - -Features: -- Transparent OAuth proxy to GitHub -- Automatic token validation via GitHub API -- User information extraction -- Minimal configuration required - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-google.mdx b/docs/python-sdk/fastmcp-server-auth-providers-google.mdx deleted file mode 100644 index 05f2400b0..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-google.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: google -sidebarTitle: google ---- - -# `fastmcp.server.auth.providers.google` - - -Google OAuth provider for FastMCP. - -This module provides a complete Google OAuth integration that's ready to use -with just a client ID and client secret. It handles all the complexity of -Google's OAuth flow, token validation, and user management. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.google import GoogleProvider - - # Simple Google OAuth protection - auth = GoogleProvider( - client_id="your-google-client-id.apps.googleusercontent.com", - client_secret="your-google-client-secret" - ) - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `GoogleTokenVerifier` - - -Token verifier for Google OAuth tokens. - -Google OAuth tokens are opaque (not JWTs), so we verify them by calling -Google's tokeninfo endpoint with the access token as a query parameter. -This returns the OAuth app ID (``aud``), granted scopes, and expiry time. -User profile data (name, picture, etc.) is fetched separately from the -v2 userinfo endpoint when the token is valid. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a Google OAuth token using the tokeninfo endpoint. - -Calls ``https://oauth2.googleapis.com/tokeninfo?access_token=TOKEN`` -to validate the token and retrieve the OAuth app ID (``aud``), granted -scopes, and expiry time. On success, fetches user profile data from -the v2 userinfo endpoint to populate name, picture, and locale claims. - - -### `GoogleProvider` - - -Complete Google OAuth provider for FastMCP. - -This provider makes it trivial to add Google OAuth protection to any -FastMCP server. Just provide your Google OAuth app credentials and -a base URL, and you're ready to go. - -Features: -- Transparent OAuth proxy to Google -- Automatic token validation via Google's tokeninfo API -- User information extraction from Google APIs -- Minimal configuration required - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx b/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx deleted file mode 100644 index 0e1e0d94e..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: in_memory -sidebarTitle: in_memory ---- - -# `fastmcp.server.auth.providers.in_memory` - -## Classes - -### `InMemoryOAuthProvider` - - -An in-memory OAuth provider for testing purposes. -It simulates the OAuth 2.1 flow locally without external calls. - - -**Methods:** - -#### `get_client` - -```python -get_client(self, client_id: str) -> OAuthClientInformationFull | None -``` - -#### `register_client` - -```python -register_client(self, client_info: OAuthClientInformationFull) -> None -``` - -#### `authorize` - -```python -authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str -``` - -Simulates user authorization and generates an authorization code. -Returns a redirect URI with the code and state. - - -#### `load_authorization_code` - -```python -load_authorization_code(self, client: OAuthClientInformationFull, authorization_code: str) -> AuthorizationCode | None -``` - -#### `exchange_authorization_code` - -```python -exchange_authorization_code(self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode) -> OAuthToken -``` - -#### `load_refresh_token` - -```python -load_refresh_token(self, client: OAuthClientInformationFull, refresh_token: str) -> RefreshToken | None -``` - -#### `exchange_refresh_token` - -```python -exchange_refresh_token(self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken -``` - -#### `load_access_token` - -```python -load_access_token(self, token: str) -> AccessToken | None -``` - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token and return access info if valid. - -This method implements the TokenVerifier protocol by delegating -to our existing load_access_token method. - -**Args:** -- `token`: The token string to validate - -**Returns:** -- AccessToken object if valid, None if invalid or expired - - -#### `revoke_token` - -```python -revoke_token(self, token: AccessToken | RefreshToken) -> None -``` - -Revokes an access or refresh token and its counterpart. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-introspection.mdx b/docs/python-sdk/fastmcp-server-auth-providers-introspection.mdx deleted file mode 100644 index 8666cc726..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-introspection.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: introspection -sidebarTitle: introspection ---- - -# `fastmcp.server.auth.providers.introspection` - - -OAuth 2.0 Token Introspection (RFC 7662) provider for FastMCP. - -This module provides token verification for opaque tokens using the OAuth 2.0 -Token Introspection protocol defined in RFC 7662. It allows FastMCP servers to -validate tokens issued by authorization servers that don't use JWT format. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier - - # Verify opaque tokens via RFC 7662 introspection - verifier = IntrospectionTokenVerifier( - introspection_url="https://auth.example.com/oauth/introspect", - client_id="your-client-id", - client_secret="your-client-secret", - required_scopes=["read", "write"] - ) - - mcp = FastMCP("My Protected Server", auth=verifier) - ``` - - -## Classes - -### `IntrospectionTokenVerifier` - - -OAuth 2.0 Token Introspection verifier (RFC 7662). - -This verifier validates opaque tokens by calling an OAuth 2.0 token introspection -endpoint. Unlike JWT verification which is stateless, token introspection requires -a network call to the authorization server for each token validation. - -The verifier authenticates to the introspection endpoint using either: -- HTTP Basic Auth (client_secret_basic, default): credentials in Authorization header -- POST body authentication (client_secret_post): credentials in request body - -Both methods are specified in RFC 6749 (OAuth 2.0) and RFC 7662 (Token Introspection). - -Use this when: -- Your authorization server issues opaque (non-JWT) tokens -- You need to validate tokens from Auth0, Okta, Keycloak, or other OAuth servers -- Your tokens require real-time revocation checking -- Your authorization server supports RFC 7662 introspection - -Caching is disabled by default to preserve real-time revocation semantics. -Set ``cache_ttl_seconds`` to enable caching and reduce load on the -introspection endpoint (e.g., ``cache_ttl_seconds=300`` for 5 minutes). - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token using OAuth 2.0 Token Introspection (RFC 7662). - -This method makes a POST request to the introspection endpoint with the token, -authenticated using the configured client authentication method (client_secret_basic -or client_secret_post). - -Results are cached in-memory to reduce load on the introspection endpoint. -Cache TTL and size are configurable via constructor parameters. - -**Args:** -- `token`: The opaque token string to validate - -**Returns:** -- AccessToken object if valid and active, None if invalid, inactive, or expired - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx b/docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx deleted file mode 100644 index 68c39df63..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: jwt -sidebarTitle: jwt ---- - -# `fastmcp.server.auth.providers.jwt` - - -TokenVerifier implementations for FastMCP. - -## Classes - -### `JWKData` - - -JSON Web Key data structure. - - -### `JWKSData` - - -JSON Web Key Set data structure. - - -### `RSAKeyPair` - - -RSA key pair for JWT testing. - - -**Methods:** - -#### `generate` - -```python -generate(cls) -> RSAKeyPair -``` - -Generate an RSA key pair for testing. - -**Returns:** -- Generated key pair - - -#### `create_token` - -```python -create_token(self, subject: str = 'fastmcp-user', issuer: str = 'https://fastmcp.example.com', audience: str | list[str] | None = None, scopes: list[str] | None = None, expires_in_seconds: int = 3600, additional_claims: dict[str, Any] | None = None, kid: str | None = None) -> str -``` - -Generate a test JWT token for testing purposes. - -**Args:** -- `subject`: Subject claim (usually user ID) -- `issuer`: Issuer claim -- `audience`: Audience claim - can be a string or list of strings (optional) -- `scopes`: List of scopes to include -- `expires_in_seconds`: Token expiration time in seconds -- `additional_claims`: Any additional claims to include -- `kid`: Key ID to include in header - - -### `JWTVerifier` - - -JWT token verifier supporting both asymmetric (RSA/ECDSA) and symmetric (HMAC) algorithms. - -This verifier validates JWT tokens using various signing algorithms: -- **Asymmetric algorithms** (RS256/384/512, ES256/384/512, PS256/384/512): - Uses public/private key pairs. Ideal for external clients and services where - only the authorization server has the private key. -- **Symmetric algorithms** (HS256/384/512): Uses a shared secret for both - signing and verification. Perfect for internal microservices and trusted - environments where the secret can be securely shared. - -Use this when: -- You have JWT tokens issued by an external service (asymmetric) -- You need JWKS support for automatic key rotation (asymmetric) -- You have internal microservices sharing a secret key (symmetric) -- Your tokens contain standard OAuth scopes and claims - - -**Methods:** - -#### `load_access_token` - -```python -load_access_token(self, token: str) -> AccessToken | None -``` - -Validate a JWT bearer token and return an AccessToken when the token is valid. - -**Args:** -- `token`: The JWT bearer token string to validate. - -**Returns:** -- AccessToken | None: An AccessToken populated from token claims if the token is valid; `None` if the token is expired, has an invalid signature or format, fails issuer/audience/scope validation, or any other validation error occurs. - - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token and return access info if valid. - -This method implements the TokenVerifier protocol by delegating -to our existing load_access_token method. - -**Args:** -- `token`: The JWT token string to validate - -**Returns:** -- AccessToken object if valid, None if invalid or expired - - -### `StaticTokenVerifier` - - -Simple static token verifier for testing and development. - -This verifier validates tokens against a predefined dictionary of valid token -strings and their associated claims. When a token string matches a key in the -dictionary, the verifier returns the corresponding claims as if the token was -validated by a real authorization server. - -Use this when: -- You're developing or testing locally without a real OAuth server -- You need predictable tokens for automated testing -- You want to simulate different users/scopes without complex setup -- You're prototyping and need simple API key-style authentication - -WARNING: Never use this in production - tokens are stored in plain text! - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify token against static token dictionary. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-keycloak.mdx b/docs/python-sdk/fastmcp-server-auth-providers-keycloak.mdx deleted file mode 100644 index e3cde2e60..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-keycloak.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: keycloak -sidebarTitle: keycloak ---- - -# `fastmcp.server.auth.providers.keycloak` - - -Keycloak authentication provider for FastMCP. - -## Classes - -### `KeycloakAuthProvider` - - -Keycloak authentication provider using Dynamic Client Registration (DCR). - -Requires Keycloak 26.6.0 or later, which includes the fix for DCR compatibility -with MCP clients (https://github.com/keycloak/keycloak/pull/45309). - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-oci.mdx b/docs/python-sdk/fastmcp-server-auth-providers-oci.mdx deleted file mode 100644 index 9f1be4fc1..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-oci.mdx +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: oci -sidebarTitle: oci ---- - -# `fastmcp.server.auth.providers.oci` - - -OCI OIDC provider for FastMCP. - -The pull request for the provider is submitted to fastmcp. - -This module provides OIDC Implementation to integrate MCP servers with OCI. -You only need OCI Identity Domain's discovery URL, client ID, client secret, and base URL. - -Post Authentication, you get OCI IAM domain access token. That is not authorized to invoke OCI control plane. -You need to exchange the IAM domain access token for OCI UPST token to invoke OCI control plane APIs. -The sample code below has get_oci_signer function that returns OCI TokenExchangeSigner object. -You can use the signer object to create OCI service object. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.oci import OCIProvider - from fastmcp.server.dependencies import get_access_token - from fastmcp.utilities.logging import get_logger - - import os - - import oci - from oci.auth.signers import TokenExchangeSigner - - logger = get_logger(__name__) - - # Load configuration from environment - config_url = os.environ.get("OCI_CONFIG_URL") # OCI IAM Domain OIDC discovery URL - client_id = os.environ.get("OCI_CLIENT_ID") # Client ID configured for the OCI IAM Domain Integrated Application - client_secret = os.environ.get("OCI_CLIENT_SECRET") # Client secret configured for the OCI IAM Domain Integrated Application - iam_guid = os.environ.get("OCI_IAM_GUID") # IAM GUID configured for the OCI IAM Domain - - # Simple OCI OIDC protection - auth = OCIProvider( - config_url=config_url, # config URL is the OCI IAM Domain OIDC discovery URL - client_id=client_id, # This is same as the client ID configured for the OCI IAM Domain Integrated Application - client_secret=client_secret, # This is same as the client secret configured for the OCI IAM Domain Integrated Application - required_scopes=["openid", "profile", "email"], - redirect_path="/auth/callback", - base_url="http://localhost:8000", - ) - - # NOTE: For production use, replace this with a thread-safe cache implementation - # such as threading.Lock-protected dict or a proper caching library - _global_token_cache = {} # In memory cache for OCI session token signer - - def get_oci_signer() -> TokenExchangeSigner: - - authntoken = get_access_token() - tokenID = authntoken.claims.get("jti") - token = authntoken.token - - # Check if the signer exists for the token ID in memory cache - cached_signer = _global_token_cache.get(tokenID) - logger.debug(f"Global cached signer: {cached_signer}") - if cached_signer: - logger.debug(f"Using globally cached signer for token ID: {tokenID}") - return cached_signer - - # If the signer is not yet created for the token then create new OCI signer object - logger.debug(f"Creating new signer for token ID: {tokenID}") - signer = TokenExchangeSigner( - jwt_or_func=token, - oci_domain_id=iam_guid.split(".")[0] if iam_guid else None, # This is same as IAM GUID configured for the OCI IAM Domain - client_id=client_id, # This is same as the client ID configured for the OCI IAM Domain Integrated Application - client_secret=client_secret, # This is same as the client secret configured for the OCI IAM Domain Integrated Application - ) - logger.debug(f"Signer {signer} created for token ID: {tokenID}") - - #Cache the signer object in memory cache - _global_token_cache[tokenID] = signer - logger.debug(f"Signer cached for token ID: {tokenID}") - - return signer - - mcp = FastMCP("My Protected Server", auth=auth) - ``` - - -## Classes - -### `OCIProvider` - - -An OCI IAM Domain provider implementation for FastMCP. - -This provider is a complete OCI integration that's ready to use with -just the configuration URL, client ID, client secret, and base URL. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-propelauth.mdx b/docs/python-sdk/fastmcp-server-auth-providers-propelauth.mdx deleted file mode 100644 index df066f733..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-propelauth.mdx +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: propelauth -sidebarTitle: propelauth ---- - -# `fastmcp.server.auth.providers.propelauth` - - -PropelAuth authentication provider for FastMCP. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth.providers.propelauth import PropelAuthProvider - - auth = PropelAuthProvider( - auth_url="https://auth.yourdomain.com", - introspection_client_id="your-client-id", - introspection_client_secret="your-client-secret", - base_url="https://your-fastmcp-server.com", - required_scopes=["read:user_data"], - ) - - mcp = FastMCP("My App", auth=auth) - ``` - - -## Classes - -### `PropelAuthTokenIntrospectionOverrides` - -### `PropelAuthProvider` - - -PropelAuth resource server provider using OAuth 2.1 token introspection. - -This provider validates access tokens via PropelAuth's introspection endpoint -and forwards authorization server metadata for OAuth discovery. - -For detailed setup instructions, see: -https://docs.propelauth.com/mcp-authentication/overview - - -**Methods:** - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get routes for this provider. - -Includes the standard routes from the RemoteAuthProvider (protected resource metadata routes (RFC 9728)), -and creates an authorization server metadata route that forwards to PropelAuth's route - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata. - - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify token and check the ``aud`` claim against the configured resource. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-scalekit.mdx b/docs/python-sdk/fastmcp-server-auth-providers-scalekit.mdx deleted file mode 100644 index cefe81c23..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-scalekit.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: scalekit -sidebarTitle: scalekit ---- - -# `fastmcp.server.auth.providers.scalekit` - - -Scalekit authentication provider for FastMCP. - -This module provides ScalekitProvider - a complete authentication solution that integrates -with Scalekit's OAuth 2.1 and OpenID Connect services, supporting Resource Server -authentication for seamless MCP client authentication. - - -## Classes - -### `ScalekitProvider` - - -Scalekit resource server provider for OAuth 2.1 authentication. - -This provider implements Scalekit integration using resource server pattern. -FastMCP acts as a protected resource server that validates access tokens issued -by Scalekit's authorization server. - -IMPORTANT SETUP REQUIREMENTS: - -1. Create an MCP Server in Scalekit Dashboard: - - Go to your [Scalekit Dashboard](https://app.scalekit.com/) - - Navigate to MCP Servers section - - Register a new MCP Server with appropriate scopes - - Ensure the Resource Identifier matches exactly what you configure as MCP URL - - Note the Resource ID - -2. Environment Configuration: - - Set SCALEKIT_ENVIRONMENT_URL (e.g., https://your-env.scalekit.com) - - Set SCALEKIT_RESOURCE_ID from your created resource - - Set BASE_URL to your FastMCP server's public URL - -For detailed setup instructions, see: -https://docs.scalekit.com/mcp/overview/ - - -**Methods:** - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get OAuth routes including Scalekit authorization server metadata forwarding. - -This returns the standard protected resource routes plus an authorization server -metadata endpoint that forwards Scalekit's OAuth metadata to clients. - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-supabase.mdx b/docs/python-sdk/fastmcp-server-auth-providers-supabase.mdx deleted file mode 100644 index 45f576a8a..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-supabase.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: supabase -sidebarTitle: supabase ---- - -# `fastmcp.server.auth.providers.supabase` - - -Supabase authentication provider for FastMCP. - -This module provides SupabaseProvider - a complete authentication solution that integrates -with Supabase Auth's JWT verification, supporting Dynamic Client Registration (DCR) -for seamless MCP client authentication. - - -## Classes - -### `SupabaseProvider` - - -Supabase metadata provider for DCR (Dynamic Client Registration). - -This provider implements Supabase Auth integration using metadata forwarding. -This approach allows Supabase to handle the OAuth flow directly while FastMCP acts -as a resource server, verifying JWTs issued by Supabase Auth. - -IMPORTANT SETUP REQUIREMENTS: - -1. Supabase Project Setup: - - Create a Supabase project at https://supabase.com - - Note your project URL (e.g., "https://abc123.supabase.co") - - Configure your JWT algorithm in Supabase Auth settings (RS256 or ES256) - - Asymmetric keys (RS256/ES256) are recommended for production - -2. JWT Verification: - - FastMCP verifies JWTs using the JWKS endpoint at {project_url}{auth_route}/.well-known/jwks.json - - JWTs are issued by {project_url}{auth_route} - - Default auth_route is "/auth/v1" (can be customized for self-hosted setups) - - Tokens are cached for up to 10 minutes by Supabase's edge servers - - Algorithm must match your Supabase Auth configuration - -3. Authorization: - - Supabase uses Row Level Security (RLS) policies for database authorization - - OAuth-level scopes are an upcoming feature in Supabase Auth - - Both approaches will be supported once scope handling is available - -For detailed setup instructions, see: -https://supabase.com/docs/guides/auth/jwts - - -**Methods:** - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get OAuth routes including Supabase authorization server metadata forwarding. - -This returns the standard protected resource routes plus an authorization server -metadata endpoint that forwards Supabase's OAuth metadata to clients. - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata. - diff --git a/docs/python-sdk/fastmcp-server-auth-providers-workos.mdx b/docs/python-sdk/fastmcp-server-auth-providers-workos.mdx deleted file mode 100644 index d050c4534..000000000 --- a/docs/python-sdk/fastmcp-server-auth-providers-workos.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: workos -sidebarTitle: workos ---- - -# `fastmcp.server.auth.providers.workos` - - -WorkOS authentication providers for FastMCP. - -This module provides two WorkOS authentication strategies: - -1. WorkOSProvider - OAuth proxy for WorkOS Connect applications (non-DCR) -2. AuthKitProvider - DCR-compliant provider for WorkOS AuthKit - -Choose based on your WorkOS setup and authentication requirements. - - -## Classes - -### `WorkOSTokenVerifier` - - -Token verifier for WorkOS OAuth tokens. - -WorkOS AuthKit tokens are opaque, so we verify them by calling -the /oauth2/userinfo endpoint to check validity and get user info. - - -**Methods:** - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify WorkOS OAuth token by calling userinfo endpoint. - - -### `WorkOSProvider` - - -Complete WorkOS OAuth provider for FastMCP. - -This provider implements WorkOS AuthKit OAuth using the OAuth Proxy pattern. -It provides OAuth2 authentication for users through WorkOS Connect applications. - -Features: -- Transparent OAuth proxy to WorkOS AuthKit -- Automatic token validation via userinfo endpoint -- User information extraction from ID tokens -- Support for standard OAuth scopes (openid, profile, email) - -Setup Requirements: -1. Create a WorkOS Connect application in your dashboard -2. Note your AuthKit domain (e.g., "https://your-app.authkit.app") -3. Configure redirect URI as: http://localhost:8000/auth/callback -4. Note your Client ID and Client Secret - - -### `AuthKitProvider` - - -AuthKit metadata provider for DCR (Dynamic Client Registration). - -This provider implements AuthKit integration using metadata forwarding -instead of OAuth proxying. This is the recommended approach for WorkOS DCR -as it allows WorkOS to handle the OAuth flow directly while FastMCP acts -as a resource server. - -IMPORTANT SETUP REQUIREMENTS: - -1. Enable Dynamic Client Registration in WorkOS Dashboard: - - Go to Applications → Configuration - - Toggle "Dynamic Client Registration" to enabled - -2. Configure your FastMCP server URL as a callback: - - Add your server URL to the Redirects tab in WorkOS dashboard - - Example: https://your-fastmcp-server.com/oauth2/callback - -For detailed setup instructions, see: -https://workos.com/docs/authkit/mcp/integrating/token-verification - -Token audience is bound to this server automatically: when the MCP -mount path becomes known (typically at ``http_app()`` construction), -``JWTVerifier.audience`` is set to the resource URL advertised in -``.well-known/oauth-protected-resource``. Enable Resource Indicators -(RFC 8707) in your WorkOS Dashboard and list that same URL — AuthKit -will then mint tokens with the matching ``aud`` claim. - - -**Methods:** - -#### `set_mcp_path` - -```python -set_mcp_path(self, mcp_path: str | None) -> None -``` - -Bind the default verifier's audience to this server's resource URL. - -AuthKit with Resource Indicators (RFC 8707) mints tokens whose ``aud`` -claim equals the resource URL the client requested — which is the URL -we advertise in ``.well-known/oauth-protected-resource``. Binding the -audience here keeps validation in lock-step with what clients are sent. - - -#### `get_routes` - -```python -get_routes(self, mcp_path: str | None = None) -> list[Route] -``` - -Get OAuth routes including AuthKit authorization server metadata forwarding. - -This returns the standard protected resource routes plus an authorization server -metadata endpoint that forwards AuthKit's OAuth metadata to clients. - -**Args:** -- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp") -This is used to advertise the resource URL in metadata. - diff --git a/docs/python-sdk/fastmcp-server-auth-redirect_validation.mdx b/docs/python-sdk/fastmcp-server-auth-redirect_validation.mdx deleted file mode 100644 index 1787326b4..000000000 --- a/docs/python-sdk/fastmcp-server-auth-redirect_validation.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: redirect_validation -sidebarTitle: redirect_validation ---- - -# `fastmcp.server.auth.redirect_validation` - - -Utilities for validating client redirect URIs in OAuth flows. - -This module provides secure redirect URI validation with wildcard support, -protecting against userinfo-based bypass attacks like http://localhost@evil.com. - - -## Functions - -### `matches_allowed_pattern` - -```python -matches_allowed_pattern(uri: str, pattern: str) -> bool -``` - - -Securely check if a URI matches an allowed pattern with wildcard support. - -This function parses both the URI and pattern as URLs, comparing each -component separately to prevent bypass attacks like userinfo injection. - -Patterns support wildcards: -- http://localhost:* matches any localhost port -- http://127.0.0.1:* matches any 127.0.0.1 port -- https://*.example.com/* matches any subdomain of example.com -- https://app.example.com/auth/* matches any path under /auth/ - -Security: Rejects URIs with userinfo (user:pass@host) which could bypass -naive string matching (e.g., http://localhost@evil.com). - -**Args:** -- `uri`: The redirect URI to validate -- `pattern`: The allowed pattern (may contain wildcards) - -**Returns:** -- True if the URI matches the pattern - - -### `validate_redirect_uri` - -```python -validate_redirect_uri(redirect_uri: str | AnyUrl | None, allowed_patterns: list[str] | None) -> bool -``` - - -Validate a redirect URI against allowed patterns. - -**Args:** -- `redirect_uri`: The redirect URI to validate -- `allowed_patterns`: List of allowed patterns. If None, all URIs are allowed (for DCR compatibility). - If empty list, no URIs are allowed. - To restrict to localhost only, explicitly pass DEFAULT_LOCALHOST_PATTERNS. - -**Returns:** -- True if the redirect URI is allowed - diff --git a/docs/python-sdk/fastmcp-server-auth-ssrf.mdx b/docs/python-sdk/fastmcp-server-auth-ssrf.mdx deleted file mode 100644 index c54ac5000..000000000 --- a/docs/python-sdk/fastmcp-server-auth-ssrf.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: ssrf -sidebarTitle: ssrf ---- - -# `fastmcp.server.auth.ssrf` - - -SSRF-safe HTTP utilities for FastMCP. - -This module provides SSRF-protected HTTP fetching with: -- DNS resolution and IP validation before requests -- DNS pinning to prevent rebinding TOCTOU attacks -- Support for both CIMD and JWKS fetches - - -## Functions - -### `format_ip_for_url` - -```python -format_ip_for_url(ip_str: str) -> str -``` - - -Format IP address for use in URL (bracket IPv6 addresses). - -IPv6 addresses must be bracketed in URLs to distinguish the address from -the port separator. For example: https://[2001:db8::1]:443/path - -**Args:** -- `ip_str`: IP address string - -**Returns:** -- IP string suitable for URL (IPv6 addresses are bracketed) - - -### `is_ip_allowed` - -```python -is_ip_allowed(ip_str: str) -> bool -``` - - -Check if an IP address is allowed (must be globally routable unicast). - -Uses ip.is_global which catches: -- Private (10.x, 172.16-31.x, 192.168.x) -- Loopback (127.x, ::1) -- Link-local (169.254.x, fe80::) - includes AWS metadata! -- Reserved, unspecified -- RFC6598 Carrier-Grade NAT (100.64.0.0/10) - can point to internal networks - -Additionally blocks multicast addresses (not caught by is_global). - -**Args:** -- `ip_str`: IP address string to check - -**Returns:** -- True if the IP is allowed (public unicast internet), False if blocked - - -### `resolve_hostname` - -```python -resolve_hostname(hostname: str, port: int = 443) -> list[str] -``` - - -Resolve hostname to IP addresses using DNS. - -**Args:** -- `hostname`: Hostname to resolve -- `port`: Port number (used for getaddrinfo) - -**Returns:** -- List of resolved IP addresses - -**Raises:** -- `SSRFError`: If resolution fails - - -### `validate_url` - -```python -validate_url(url: str, require_path: bool = False) -> ValidatedURL -``` - - -Validate URL for SSRF and resolve to IPs. - -**Args:** -- `url`: URL to validate -- `require_path`: If True, require non-root path (for CIMD) - -**Returns:** -- ValidatedURL with resolved IPs - -**Raises:** -- `SSRFError`: If URL is invalid or resolves to blocked IPs - - -### `ssrf_safe_fetch` - -```python -ssrf_safe_fetch(url: str) -> bytes -``` - - -Fetch URL with comprehensive SSRF protection and DNS pinning. - -Security measures: -1. HTTPS only -2. DNS resolution with IP validation -3. Connects to validated IP directly (DNS pinning prevents rebinding) -4. Response size limit -5. Redirects disabled -6. Overall timeout - -**Args:** -- `url`: URL to fetch -- `require_path`: If True, require non-root path -- `max_size`: Maximum response size in bytes (default 5KB) -- `timeout`: Per-operation timeout in seconds -- `overall_timeout`: Overall timeout for entire operation - -**Returns:** -- Response body as bytes - -**Raises:** -- `SSRFError`: If SSRF validation fails -- `SSRFFetchError`: If fetch fails - - -### `ssrf_safe_fetch_response` - -```python -ssrf_safe_fetch_response(url: str) -> SSRFFetchResponse -``` - - -Fetch URL with SSRF protection and return response metadata. - -This is equivalent to :func:`ssrf_safe_fetch` but returns response headers -and status code, and supports conditional request headers. - - -## Classes - -### `SSRFError` - - -Raised when an SSRF protection check fails. - - -### `SSRFFetchError` - - -Raised when SSRF-safe fetch fails. - - -### `ValidatedURL` - - -A URL that has been validated for SSRF with resolved IPs. - - -### `SSRFFetchResponse` - - -Response payload from an SSRF-safe fetch. - diff --git a/docs/python-sdk/fastmcp-server-context.mdx b/docs/python-sdk/fastmcp-server-context.mdx deleted file mode 100644 index 2b9940ca1..000000000 --- a/docs/python-sdk/fastmcp-server-context.mdx +++ /dev/null @@ -1,755 +0,0 @@ ---- -title: context -sidebarTitle: context ---- - -# `fastmcp.server.context` - -## Functions - -### `set_transport` - -```python -set_transport(transport: TransportType) -> Token[TransportType | None] -``` - - -Set the current transport type. Returns token for reset. - - -### `reset_transport` - -```python -reset_transport(token: Token[TransportType | None]) -> None -``` - - -Reset transport to previous value. - - -### `set_context` - -```python -set_context(context: Context) -> Generator[Context, None, None] -``` - -## Classes - -### `LogData` - - -Data object for passing log arguments to client-side handlers. - -This provides an interface to match the Python standard library logging, -for compatibility with structured logging. - - -### `Context` - - -Context object providing access to MCP capabilities. - -This provides a cleaner interface to MCP's RequestContext functionality. -It gets injected into tool and resource functions that request it via type hints. - -To use context in a tool function, add a parameter with the Context type annotation: - -```python -@server.tool -async def my_tool(x: int, ctx: Context) -> str: - # Log messages to the client - await ctx.info(f"Processing {x}") - await ctx.debug("Debug info") - await ctx.warning("Warning message") - await ctx.error("Error message") - - # Report progress - await ctx.report_progress(50, 100, "Processing") - - # Access resources - data = await ctx.read_resource("resource://data") - - # Get request info - request_id = ctx.request_id - client_id = ctx.client_id - - # Manage state across the session (persists across requests) - await ctx.set_state("key", "value") - value = await ctx.get_state("key") - - # Store non-serializable values for the current request only - await ctx.set_state("client", http_client, serializable=False) - - return str(x) -``` - -State Management: -Context provides session-scoped state that persists across requests within -the same MCP session. State is automatically keyed by session, ensuring -isolation between different clients. - -State set during `on_initialize` middleware will persist to subsequent tool -calls when using the same session object (STDIO, SSE, single-server HTTP). -For distributed/serverless HTTP deployments where different machines handle -the init and tool calls, state is isolated by the mcp-session-id header. - -The context parameter name can be anything as long as it's annotated with Context. -The context is optional - tools that don't need it can omit the parameter. - - -**Methods:** - -#### `is_background_task` - -```python -is_background_task(self) -> bool -``` - -True when this context is running in a background task (Docket worker). - -When True, certain operations like elicit() and sample() will use -task-aware implementations that can pause the task and wait for -client input. - - -#### `task_id` - -```python -task_id(self) -> str | None -``` - -Get the background task ID if running in a background task. - -Returns None if not running in a background task context. - - -#### `origin_request_id` - -```python -origin_request_id(self) -> str | None -``` - -Get the request ID that originated this execution, if available. - -In foreground request mode, this is the current request_id. -In background task mode, this is the request_id captured when the task -was submitted, if one was available. - - -#### `fastmcp` - -```python -fastmcp(self) -> FastMCP -``` - -Get the FastMCP instance. - - -#### `request_context` - -```python -request_context(self) -> RequestContext[ServerSession, Any, Request] | None -``` - -Access to the underlying request context. - -Returns None when the MCP session has not been established yet. -Returns the full RequestContext once the MCP session is available. - -For HTTP request access in middleware, use `get_http_request()` from fastmcp.server.dependencies, -which works whether or not the MCP session is available. - -Example in middleware: -```python -async def on_request(self, context, call_next): - ctx = context.fastmcp_context - if ctx.request_context: - # MCP session available - can access session_id, request_id, etc. - session_id = ctx.session_id - else: - # MCP session not available yet - use HTTP helpers - from fastmcp.server.dependencies import get_http_request - request = get_http_request() - return await call_next(context) -``` - - -#### `lifespan_context` - -```python -lifespan_context(self) -> dict[str, Any] -``` - -Access the server's lifespan context. - -Returns the context dict yielded by the server's lifespan function. -Returns an empty dict if no lifespan was configured or if the MCP -session is not yet established. - -In background tasks (Docket workers), where request_context is not -available, falls back to reading from the FastMCP server's lifespan -result directly. - -Example: -```python -@server.tool -def my_tool(ctx: Context) -> str: - db = ctx.lifespan_context.get("db") - if db: - return db.query("SELECT 1") - return "No database connection" -``` - - -#### `report_progress` - -```python -report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None -``` - -Report progress for the current operation. - -Works in both foreground (MCP progress notifications) and background -(Docket task execution) contexts. - -**Args:** -- `progress`: Current progress value e.g. 24 -- `total`: Optional total value e.g. 100 -- `message`: Optional status message describing current progress - - -#### `list_resources` - -```python -list_resources(self) -> list[SDKResource] -``` - -List all available resources from the server. - -**Returns:** -- List of Resource objects available on the server - - -#### `list_prompts` - -```python -list_prompts(self) -> list[SDKPrompt] -``` - -List all available prompts from the server. - -**Returns:** -- List of Prompt objects available on the server - - -#### `get_prompt` - -```python -get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult -``` - -Get a prompt by name with optional arguments. - -**Args:** -- `name`: The name of the prompt to get -- `arguments`: Optional arguments to pass to the prompt - -**Returns:** -- The prompt result - - -#### `read_resource` - -```python -read_resource(self, uri: str | AnyUrl) -> ResourceResult -``` - -Read a resource by URI. - -**Args:** -- `uri`: Resource URI to read - -**Returns:** -- ResourceResult with contents - - -#### `log` - -```python -log(self, message: str, level: LoggingLevel | None = None, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None -``` - -Send a log message to the client. - -Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`. - -**Args:** -- `message`: Log message -- `level`: Optional log level. One of "debug", "info", "notice", "warning", "error", "critical", -"alert", or "emergency". Default is "info". -- `logger_name`: Optional logger name -- `extra`: Optional mapping for additional arguments - - -#### `transport` - -```python -transport(self) -> TransportType | None -``` - -Get the current transport type. - -Returns the transport type used to run this server: "stdio", "sse", -or "streamable-http". Returns None if called outside of a server context. - - -#### `client_supports_extension` - -```python -client_supports_extension(self, extension_id: str) -> bool -``` - -Check whether the connected client supports a given MCP extension. - -Inspects the ``extensions`` extra field on ``ClientCapabilities`` -sent by the client during initialization. - -Returns ``False`` when no session is available (e.g., outside a -request context) or when the client did not advertise the extension. - -Example:: - - from fastmcp.apps.config import UI_EXTENSION_ID - - @mcp.tool - async def my_tool(ctx: Context) -> str: - if ctx.client_supports_extension(UI_EXTENSION_ID): - return "UI-capable client" - return "text-only client" - - -#### `client_id` - -```python -client_id(self) -> str | None -``` - -Get the client ID if available. - - -#### `request_id` - -```python -request_id(self) -> str -``` - -Get the unique ID for this request. - -Raises RuntimeError if MCP request context is not available. - - -#### `session_id` - -```python -session_id(self) -> str -``` - -Get the MCP session ID for ALL transports. - -Returns the session ID that can be used as a key for session-based -data storage (e.g., Redis) to share data between tool calls within -the same client session. - -**Returns:** -- The session ID for StreamableHTTP transports, or a generated ID -- for other transports. - - -#### `session` - -```python -session(self) -> ServerSession -``` - -Access to the underlying session for advanced usage. - -In request mode: Returns the session from the active request context. -In background task mode: Returns the session stored at Context creation. - -Raises RuntimeError if no session is available. - - -#### `debug` - -```python -debug(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None -``` - -Send a `DEBUG`-level message to the connected MCP Client. - -Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`. - - -#### `info` - -```python -info(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None -``` - -Send a `INFO`-level message to the connected MCP Client. - -Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`. - - -#### `warning` - -```python -warning(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None -``` - -Send a `WARNING`-level message to the connected MCP Client. - -Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`. - - -#### `error` - -```python -error(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None -``` - -Send a `ERROR`-level message to the connected MCP Client. - -Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`. - - -#### `list_roots` - -```python -list_roots(self) -> list[Root] -``` - -List the roots available to the server, as indicated by the client. - - -#### `send_notification` - -```python -send_notification(self, notification: mcp.types.ServerNotificationType) -> None -``` - -Send a notification to the client immediately. - -**Args:** -- `notification`: An MCP notification instance (e.g., ToolListChangedNotification()) - - -#### `close_sse_stream` - -```python -close_sse_stream(self) -> None -``` - -Close the current response stream to trigger client reconnection. - -When using StreamableHTTP transport with an EventStore configured, this -method gracefully closes the HTTP connection for the current request. -The client will automatically reconnect (after `retry_interval` milliseconds) -and resume receiving events from where it left off via the EventStore. - -This is useful for long-running operations to avoid load balancer timeouts. -Instead of holding a connection open for minutes, you can periodically close -and let the client reconnect. - - -#### `sample_step` - -```python -sample_step(self, messages: str | Sequence[str | SamplingMessage]) -> SampleStep -``` - -Make a single LLM sampling call. - -This is a stateless function that makes exactly one LLM call and optionally -executes any requested tools. Use this for fine-grained control over the -sampling loop. - -**Args:** -- `messages`: The message(s) to send. Can be a string, list of strings, -or list of SamplingMessage objects. -- `system_prompt`: Optional system prompt for the LLM. -- `temperature`: Optional sampling temperature. -- `max_tokens`: Maximum tokens to generate. Defaults to 512. -- `model_preferences`: Optional model preferences. -- `tools`: Optional list of tools the LLM can use. -- `tool_choice`: Tool choice mode ("auto", "required", or "none"). -- `execute_tools`: If True (default), execute tool calls and append results -to history. If False, return immediately with tool_calls available -in the step for manual execution. -- `mask_error_details`: If True, mask detailed error messages from tool -execution. When None (default), uses the global settings value. -Tools can raise ToolError to bypass masking. -- `tool_concurrency`: Controls parallel execution of tools\: -- None (default)\: Sequential execution (one at a time) -- 0\: Unlimited parallel execution -- N > 0\: Execute at most N tools concurrently -If any tool has sequential=True, all tools execute sequentially -regardless of this setting. - -**Returns:** -- SampleStep containing: -- - .response: The raw LLM response -- - .history: Messages including input, assistant response, and tool results -- - .is_tool_use: True if the LLM requested tool execution -- - .tool_calls: List of tool calls (if any) -- - .text: The text content (if any) - - -#### `sample` - -```python -sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] -``` - -Overload: With result_type, returns SamplingResult[ResultT]. - - -#### `sample` - -```python -sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[str] -``` - -Overload: Without result_type, returns SamplingResult[str]. - - -#### `sample` - -```python -sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] | SamplingResult[str] -``` - -Send a sampling request to the client and await the response. - -This method runs to completion automatically. When tools are provided, -it executes a tool loop: if the LLM returns a tool use request, the tools -are executed and the results are sent back to the LLM. This continues -until the LLM provides a final text response. - -When result_type is specified, a synthetic `final_response` tool is -created. The LLM calls this tool to provide the structured response, -which is validated against the result_type and returned as `.result`. - -For fine-grained control over the sampling loop, use sample_step() instead. - -**Args:** -- `messages`: The message(s) to send. Can be a string, list of strings, -or list of SamplingMessage objects. -- `system_prompt`: Optional system prompt for the LLM. -- `temperature`: Optional sampling temperature. -- `max_tokens`: Maximum tokens to generate. Defaults to 512. -- `model_preferences`: Optional model preferences. -- `tools`: Optional list of tools the LLM can use. Accepts plain -functions or SamplingTools. -- `result_type`: Optional type for structured output. When specified, -a synthetic `final_response` tool is created and the LLM's -response is validated against this type. -- `mask_error_details`: If True, mask detailed error messages from tool -execution. When None (default), uses the global settings value. -Tools can raise ToolError to bypass masking. -- `tool_concurrency`: Controls parallel execution of tools\: -- None (default)\: Sequential execution (one at a time) -- 0\: Unlimited parallel execution -- N > 0\: Execute at most N tools concurrently -If any tool has sequential=True, all tools execute sequentially -regardless of this setting. - -**Returns:** -- SamplingResult[T] containing: -- - .text: The text representation (raw text or JSON for structured) -- - .result: The typed result (str for text, parsed object for structured) -- - .history: All messages exchanged during sampling - - -#### `elicit` - -```python -elicit(self, message: str, response_type: None) -> AcceptedElicitation[dict[str, Any]] | DeclinedElicitation | CancelledElicitation -``` - -#### `elicit` - -```python -elicit(self, message: str, response_type: type[T]) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation -``` - -#### `elicit` - -```python -elicit(self, message: str, response_type: list[str]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation -``` - -#### `elicit` - -```python -elicit(self, message: str, response_type: dict[str, dict[str, str]]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation -``` - -#### `elicit` - -```python -elicit(self, message: str, response_type: list[list[str]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation -``` - -#### `elicit` - -```python -elicit(self, message: str, response_type: list[dict[str, dict[str, str]]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation -``` - -#### `elicit` - -```python -elicit(self, message: str, response_type: type[T] | list[str] | dict[str, dict[str, str]] | list[list[str]] | list[dict[str, dict[str, str]]] | None = None) -> AcceptedElicitation[T] | AcceptedElicitation[dict[str, Any]] | AcceptedElicitation[str] | AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation -``` - -Send an elicitation request to the client and await the response. - -Call this method at any time to request additional information from -the user through the client. The client must support elicitation, -or the request will error. - -Note that the MCP protocol only supports simple object schemas with -primitive types. You can provide a dataclass, TypedDict, or BaseModel to -comply. If you provide a primitive type, an object schema with a single -"value" field will be generated for the MCP interaction and -automatically deconstructed into the primitive type upon response. - -Passing ``response_type=None`` (or omitting it) is deprecated and will -be removed in a future version. The resulting empty-schema form-mode -request is ambiguous and causes some clients (e.g. VS Code) to hang on -an empty form. Pass an explicit ``response_type`` describing the data -you want back. - -**Args:** -- `message`: A human-readable message explaining what information is needed -- `response_type`: The type of the response, which should be a primitive -type or dataclass or BaseModel. If it is a primitive type, an -object schema with a single "value" field will be generated. -- `response_title`: Optional label to display for the wrapped ``value`` -field when ``response_type`` is a scalar, Literal, Enum, or one -of the dict/list shorthand forms. Overrides the auto-generated -"Value" label. Raises ``TypeError`` if passed with a BaseModel, -dataclass, or ``None`` response type (use ``Field(title=...)`` -on the model instead). -- `response_description`: Optional description to attach to the wrapped -``value`` field. Same scope rules as ``response_title``. - - -#### `set_state` - -```python -set_state(self, key: str, value: Any) -> None -``` - -Set a value in the state store. - -By default, values are stored in the session-scoped state store and -persist across requests within the same MCP session. Values must be -JSON-serializable (dicts, lists, strings, numbers, etc.). - -For non-serializable values (e.g., HTTP clients, database connections), -pass ``serializable=False``. These values are stored in a request-scoped -dict and only live for the current MCP request (tool call, resource -read, or prompt render). They will not be available in subsequent -requests. - -The key is automatically prefixed with the session identifier. - - -#### `get_state` - -```python -get_state(self, key: str) -> Any -``` - -Get a value from the state store. - -Checks request-scoped state first (set with ``serializable=False``), -then falls back to the session-scoped state store. - -Returns None if the key is not found. - - -#### `delete_state` - -```python -delete_state(self, key: str) -> None -``` - -Delete a value from the state store. - -Removes from both request-scoped and session-scoped stores. - - -#### `enable_components` - -```python -enable_components(self) -> None -``` - -Enable components matching criteria for this session only. - -Session rules override global transforms. Rules accumulate - each call -adds a new rule to the session. Later marks override earlier ones -(Visibility transform semantics). - -Sends notifications to this session only: ToolListChangedNotification, -ResourceListChangedNotification, and PromptListChangedNotification. - -**Args:** -- `names`: Component names or URIs to match. -- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}). -- `version`: Component version spec to match. -- `tags`: Tags to match (component must have at least one). -- `components`: Component types to match (e.g., {"tool", "prompt"}). -- `match_all`: If True, matches all components regardless of other criteria. - - -#### `disable_components` - -```python -disable_components(self) -> None -``` - -Disable components matching criteria for this session only. - -Session rules override global transforms. Rules accumulate - each call -adds a new rule to the session. Later marks override earlier ones -(Visibility transform semantics). - -Sends notifications to this session only: ToolListChangedNotification, -ResourceListChangedNotification, and PromptListChangedNotification. - -**Args:** -- `names`: Component names or URIs to match. -- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}). -- `version`: Component version spec to match. -- `tags`: Tags to match (component must have at least one). -- `components`: Component types to match (e.g., {"tool", "prompt"}). -- `match_all`: If True, matches all components regardless of other criteria. - - -#### `reset_visibility` - -```python -reset_visibility(self) -> None -``` - -Clear all session visibility rules. - -Use this to reset session visibility back to global defaults. - -Sends notifications to this session only: ToolListChangedNotification, -ResourceListChangedNotification, and PromptListChangedNotification. - diff --git a/docs/python-sdk/fastmcp-server-dependencies.mdx b/docs/python-sdk/fastmcp-server-dependencies.mdx deleted file mode 100644 index 94c31f459..000000000 --- a/docs/python-sdk/fastmcp-server-dependencies.mdx +++ /dev/null @@ -1,576 +0,0 @@ ---- -title: dependencies -sidebarTitle: dependencies ---- - -# `fastmcp.server.dependencies` - - -Dependency injection for FastMCP. - -DI features (Depends, CurrentContext, CurrentFastMCP) work without pydocket -using the uncalled-for DI engine. Only task-related dependencies (CurrentDocket, -CurrentWorker) and background task execution require fastmcp[tasks]. - - -## Functions - -### `is_docket_available` - -```python -is_docket_available() -> bool -``` - - -Check if a compatible pydocket (>= 0.19.0) is installed and importable. - -Three things have to be true for fastmcp's task features to work: - 1. pydocket distribution metadata is discoverable - 2. its version is at least ``_MIN_DOCKET_VERSION`` (older versions are - missing symbols like ``docket.dependencies.current_execution``, - which fastmcp imports on the request hot path) - 3. the package actually imports — guards against broken/partial - installs where metadata exists but ``import docket`` blows up - -Any of those failing means we treat docket as unavailable and fall back -to the no-tasks code paths instead of crashing deep inside a request. - - -### `require_docket` - -```python -require_docket(feature: str) -> None -``` - - -Raise ImportError with install instructions if docket not available. - -**Args:** -- `feature`: Description of what requires docket (e.g., "`task=True`", - "CurrentDocket()"). Will be included in the error message. - - -### `transform_context_annotations` - -```python -transform_context_annotations(fn: Callable[..., Any]) -> Callable[..., Any] -``` - - -Transform ctx: Context into ctx: Context = CurrentContext(). - -Transforms ALL params typed as Context to use Docket's DI system, -unless they already have a Dependency-based default (like CurrentContext()). - -This unifies the legacy type annotation DI with Docket's Depends() system, -allowing both patterns to work through a single resolution path. - -Note: Only POSITIONAL_OR_KEYWORD parameters are reordered (params with defaults -after those without). KEYWORD_ONLY parameters keep their position since Python -allows them to have defaults in any order. - -**Args:** -- `fn`: Function to transform - -**Returns:** -- Function with modified signature (same function object, updated __signature__) - - -### `get_context` - -```python -get_context() -> Context -``` - - -Get the current FastMCP Context instance directly. - - -### `get_server` - -```python -get_server() -> FastMCP -``` - - -Get the current FastMCP server instance directly. - -In a background-task worker, checks the task-server map first so that -mounted-child tasks resolve to the child server (not the parent that -started the worker). - -**Returns:** -- The active FastMCP server - -**Raises:** -- `RuntimeError`: If no server in context - - -### `get_http_request` - -```python -get_http_request() -> Request -``` - - -Get the current HTTP request. - -Tries MCP SDK's request_ctx first, then falls back to FastMCP's HTTP context. -In background tasks, returns a synthetic request populated with the -snapshotted headers from the originating HTTP request. - - -### `get_http_headers` - -```python -get_http_headers(include_all: bool = False, include: set[str] | None = None) -> dict[str, str] -``` - - -Extract headers from the current HTTP request if available. - -Never raises an exception, even if there is no active HTTP request (in which case -an empty dict is returned). - -By default, strips problematic headers like `content-length` and `authorization` -that cause issues if forwarded to downstream services. If `include_all` is True, -all headers are returned. - -The `include` parameter allows specific headers to be included even if they would -normally be excluded. This is useful for proxy transports that need to forward -authorization headers to upstream MCP servers. - - -### `get_access_token` - -```python -get_access_token() -> AccessToken | None -``` - - -Get the FastMCP access token from the current context. - -This function first tries to get the token from the current HTTP request's scope, -which is more reliable for long-lived connections where the SDK's auth_context_var -may become stale after token refresh. Falls back to the SDK's context var if no -request is available. In background tasks (Docket workers), falls back to the -token snapshot stored in Redis at task submission time. - -**Returns:** -- The access token if an authenticated user is available, None otherwise. - - -### `without_injected_parameters` - -```python -without_injected_parameters(fn: Callable[..., Any]) -> Callable[..., Any] -``` - - -Create a wrapper function without injected parameters. - -Returns a wrapper that excludes Context and Docket dependency parameters, -making it safe to use with Pydantic TypeAdapter for schema generation and -validation. The wrapper internally handles all dependency resolution and -Context injection when called. - -Handles: -- Legacy Context injection (always works) -- Depends() injection (always works - uses docket or vendored DI engine) - -**Args:** -- `fn`: Original function with Context and/or dependencies -- `run_in_thread`: For sync ``fn``, whether to dispatch the call to a worker -thread after resolving dependencies. Defaults to True. Set to False -to call ``fn`` inline on the event loop thread — required for -thread-affinity libraries (e.g. Windows COM). Ignored for async fns. - -**Returns:** -- Async wrapper function without injected parameters - - -### `resolve_dependencies` - -```python -resolve_dependencies(fn: Callable[..., Any], arguments: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None] -``` - - -Resolve dependencies for a FastMCP function. - -This function: -1. Filters out any dependency parameter names from user arguments (security) -2. Resolves Depends() parameters via the DI system - -The filtering prevents external callers from overriding injected parameters by -providing values for dependency parameter names. This is a security feature. - -Note: Context injection is handled via transform_context_annotations() which -converts `ctx: Context` to `ctx: Context = Depends(get_context)` at registration -time, so all injection goes through the unified DI system. - -**Args:** -- `fn`: The function to resolve dependencies for -- `arguments`: User arguments (may contain keys that match dependency names, - which will be filtered out) - - -### `CurrentContext` - -```python -CurrentContext() -> Context -``` - - -Get the current FastMCP Context instance. - -This dependency provides access to the active FastMCP Context for the -current MCP operation (tool/resource/prompt call). - -**Returns:** -- A dependency that resolves to the active Context instance - -**Raises:** -- `RuntimeError`: If no active context found (during resolution) - - -### `OptionalCurrentContext` - -```python -OptionalCurrentContext() -> Context | None -``` - - -Get the current FastMCP Context, or None when no context is active. - - -### `CurrentDocket` - -```python -CurrentDocket() -> Docket -``` - - -Get the current Docket instance managed by FastMCP. - -This dependency provides access to the Docket instance that FastMCP -automatically creates for background task scheduling. - -**Returns:** -- A dependency that resolves to the active Docket instance - -**Raises:** -- `RuntimeError`: If not within a FastMCP server context -- `ImportError`: If fastmcp[tasks] not installed - - -### `CurrentWorker` - -```python -CurrentWorker() -> Worker -``` - - -Get the current Docket Worker instance managed by FastMCP. - -This dependency provides access to the Worker instance that FastMCP -automatically creates for background task processing. - -**Returns:** -- A dependency that resolves to the active Worker instance - -**Raises:** -- `RuntimeError`: If not within a FastMCP server context -- `ImportError`: If fastmcp[tasks] not installed - - -### `CurrentFastMCP` - -```python -CurrentFastMCP() -> FastMCP -``` - - -Get the current FastMCP server instance. - -This dependency provides access to the active FastMCP server. - -**Returns:** -- A dependency that resolves to the active FastMCP server - -**Raises:** -- `RuntimeError`: If no server in context (during resolution) - - -### `CurrentRequest` - -```python -CurrentRequest() -> Request -``` - - -Get the current HTTP request. - -This dependency provides access to the Starlette Request object for the -current HTTP request. Only available when running over HTTP transports -(SSE or Streamable HTTP). - -**Returns:** -- A dependency that resolves to the active Starlette Request - -**Raises:** -- `RuntimeError`: If no HTTP request in context (e.g., STDIO transport) - - -### `CurrentHeaders` - -```python -CurrentHeaders() -> dict[str, str] -``` - - -Get the current HTTP request headers. - -This dependency provides access to the HTTP headers for the current request, -including the authorization header. Returns an empty dictionary when no HTTP -request is available, making it safe to use in code that might run over any -transport. - -**Returns:** -- A dependency that resolves to a dictionary of header name -> value - - -### `CurrentAccessToken` - -```python -CurrentAccessToken() -> AccessToken -``` - - -Get the current access token for the authenticated user. - -This dependency provides access to the AccessToken for the current -authenticated request. Raises an error if no authentication is present. - -**Returns:** -- A dependency that resolves to the active AccessToken - -**Raises:** -- `RuntimeError`: If no authenticated user (use get_access_token() for optional) - - -### `TokenClaim` - -```python -TokenClaim(name: str) -> str -``` - - -Get a specific claim from the access token. - -This dependency extracts a single claim value from the current access token. -It's useful for getting user identifiers, roles, or other token claims -without needing the full token object. - -**Args:** -- `name`: The name of the claim to extract (e.g., "oid", "sub", "email") - -**Returns:** -- A dependency that resolves to the claim value as a string - -**Raises:** -- `RuntimeError`: If no access token is available or claim is missing - - -## Classes - -### `ProgressLike` - - -Protocol for progress tracking interface. - -Defines the common interface between InMemoryProgress (server context) -and Docket's Progress (worker context). - - -**Methods:** - -#### `current` - -```python -current(self) -> int | None -``` - -Current progress value. - - -#### `total` - -```python -total(self) -> int -``` - -Total/target progress value. - - -#### `message` - -```python -message(self) -> str | None -``` - -Current progress message. - - -#### `set_total` - -```python -set_total(self, total: int) -> None -``` - -Set the total/target value for progress tracking. - - -#### `increment` - -```python -increment(self, amount: int = 1) -> None -``` - -Atomically increment the current progress value. - - -#### `set_message` - -```python -set_message(self, message: str | None) -> None -``` - -Update the progress status message. - - -### `InMemoryProgress` - - -In-memory progress tracker for immediate tool execution. - -Provides the same interface as Docket's Progress but stores state in memory -instead of Redis. Useful for testing and immediate execution where -progress doesn't need to be observable across processes. - - -**Methods:** - -#### `current` - -```python -current(self) -> int | None -``` - -#### `total` - -```python -total(self) -> int -``` - -#### `message` - -```python -message(self) -> str | None -``` - -#### `set_total` - -```python -set_total(self, total: int) -> None -``` - -Set the total/target value for progress tracking. - - -#### `increment` - -```python -increment(self, amount: int = 1) -> None -``` - -Atomically increment the current progress value. - - -#### `set_message` - -```python -set_message(self, message: str | None) -> None -``` - -Update the progress status message. - - -### `Progress` - - -Progress dependency that works in both server and worker contexts. - -In a Docket worker, delegates to the execution's Redis-backed progress -(observable across processes). Otherwise, uses in-memory tracking. - -The shared default instance acts as a stateless factory — ``__aenter__`` -creates a fresh ``Progress`` per invocation so concurrent tasks never -share mutable state. - - -**Methods:** - -#### `current` - -```python -current(self) -> int | None -``` - -Current progress value. - - -#### `total` - -```python -total(self) -> int -``` - -Total/target progress value. - - -#### `message` - -```python -message(self) -> str | None -``` - -Current progress message. - - -#### `set_total` - -```python -set_total(self, total: int) -> None -``` - -Set the total/target value for progress tracking. - - -#### `increment` - -```python -increment(self, amount: int = 1) -> None -``` - -Atomically increment the current progress value. - - -#### `set_message` - -```python -set_message(self, message: str | None) -> None -``` - -Update the progress status message. - diff --git a/docs/python-sdk/fastmcp-server-elicitation.mdx b/docs/python-sdk/fastmcp-server-elicitation.mdx deleted file mode 100644 index 8b33a04c2..000000000 --- a/docs/python-sdk/fastmcp-server-elicitation.mdx +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: elicitation -sidebarTitle: elicitation ---- - -# `fastmcp.server.elicitation` - -## Functions - -### `parse_elicit_response_type` - -```python -parse_elicit_response_type(response_type: Any, response_title: str | None = None, response_description: str | None = None) -> ElicitConfig -``` - - -Parse response_type into schema and handling configuration. - -Supports multiple syntaxes: -- None: Empty object schema, expect empty response -- dict: `{"low": {"title": "..."}}` -> single-select titled enum -- list patterns: - - `[["a", "b"]]` -> multi-select untitled - - `[{"low": {...}}]` -> multi-select titled - - `["a", "b"]` -> single-select untitled -- `list[X]` type annotation: multi-select with type -- Scalar types (bool, int, float, str, Literal, Enum): single value -- Other types (dataclass, BaseModel): use directly - -The ``response_title`` and ``response_description`` arguments customize the -label and description of the wrapped ``value`` property for the scalar/dict/list -shorthand forms. They are only valid when FastMCP is wrapping the response -type; passing them with a full BaseModel/dataclass (or ``None``) raises -``TypeError``, because in those cases the user already controls field -metadata via ``Field(title=..., description=...)``. - - -### `handle_elicit_accept` - -```python -handle_elicit_accept(config: ElicitConfig, content: Any) -> AcceptedElicitation[Any] -``` - - -Handle an accepted elicitation response. - -**Args:** -- `config`: The elicitation configuration from parse_elicit_response_type -- `content`: The response content from the client - -**Returns:** -- AcceptedElicitation with the extracted/validated data - - -### `get_elicitation_schema` - -```python -get_elicitation_schema(response_type: type[T]) -> dict[str, Any] -``` - - -Get the schema for an elicitation response. - -**Args:** -- `response_type`: The type of the response - - -### `validate_elicitation_json_schema` - -```python -validate_elicitation_json_schema(schema: dict[str, Any]) -> None -``` - - -Validate that a JSON schema follows MCP elicitation requirements. - -This ensures the schema is compatible with MCP elicitation requirements: -- Must be an object schema -- Must only contain primitive field types (string, number, integer, boolean) -- Must be flat (no nested objects or arrays of objects) -- Allows const fields (for Literal types) and enum fields (for Enum types) -- Only primitive types and their nullable variants are allowed - -**Args:** -- `schema`: The JSON schema to validate - -**Raises:** -- `TypeError`: If the schema doesn't meet MCP elicitation requirements - - -## Classes - -### `ElicitationJsonSchema` - - -Custom JSON schema generator for MCP elicitation that always inlines enums. - -MCP elicitation requires inline enum schemas without $ref/$defs references. -This generator ensures enums are always generated inline for compatibility. -Optionally adds enumNames for better UI display when available. - - -**Methods:** - -#### `generate_inner` - -```python -generate_inner(self, schema: core_schema.CoreSchema) -> JsonSchemaValue -``` - -Override to prevent ref generation for enums and handle list schemas. - - -#### `list_schema` - -```python -list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue -``` - -Generate schema for list types, detecting enum items for multi-select. - - -#### `enum_schema` - -```python -enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue -``` - -Generate inline enum schema. - -Always generates enum pattern: `{"enum": [value, ...]}` -Titled enums are handled separately via dict-based syntax in ctx.elicit(). - - -### `AcceptedElicitation` - - -Result when user accepts the elicitation. - - -### `ScalarElicitationType` - -### `ElicitConfig` - - -Configuration for an elicitation request. - -**Attributes:** -- `schema`: The JSON schema to send to the client -- `response_type`: The type to validate responses with (None for raw schemas) -- `is_raw`: True if schema was built directly (extract "value" from response) - diff --git a/docs/python-sdk/fastmcp-server-event_store.mdx b/docs/python-sdk/fastmcp-server-event_store.mdx deleted file mode 100644 index 004e94405..000000000 --- a/docs/python-sdk/fastmcp-server-event_store.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: event_store -sidebarTitle: event_store ---- - -# `fastmcp.server.event_store` - - -EventStore implementation backed by AsyncKeyValue. - -This module provides an EventStore implementation that enables SSE polling/resumability -for Streamable HTTP transports. Events are stored using the key_value package's -AsyncKeyValue protocol, allowing users to configure any compatible backend -(in-memory, Redis, etc.) following the same pattern as ResponseCachingMiddleware. - - -## Classes - -### `EventEntry` - - -Stored event entry. - - -### `StreamEventList` - - -List of event IDs for a stream. - - -### `EventStore` - - -EventStore implementation backed by AsyncKeyValue. - -Enables SSE polling/resumability by storing events that can be replayed -when clients reconnect. Works with any AsyncKeyValue backend (memory, Redis, etc.) -following the same pattern as ResponseCachingMiddleware and OAuthProxy. - -**Args:** -- `storage`: AsyncKeyValue backend. Defaults to MemoryStore. -- `max_events_per_stream`: Maximum events to retain per stream. Default 100. -- `ttl`: Event TTL in seconds. Default 3600 (1 hour). Set to None for no expiration. - - -**Methods:** - -#### `store_event` - -```python -store_event(self, stream_id: StreamId, message: JSONRPCMessage | None) -> EventId -``` - -Store an event and return its ID. - -**Args:** -- `stream_id`: ID of the stream the event belongs to -- `message`: The JSON-RPC message to store, or None for priming events - -**Returns:** -- The generated event ID for the stored event - - -#### `replay_events_after` - -```python -replay_events_after(self, last_event_id: EventId, send_callback: EventCallback) -> StreamId | None -``` - -Replay events that occurred after the specified event ID. - -**Args:** -- `last_event_id`: The ID of the last event the client received -- `send_callback`: A callback function to send events to the client - -**Returns:** -- The stream ID of the replayed events, or None if the event ID was not found - diff --git a/docs/python-sdk/fastmcp-server-http.mdx b/docs/python-sdk/fastmcp-server-http.mdx deleted file mode 100644 index f4e5d45bc..000000000 --- a/docs/python-sdk/fastmcp-server-http.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: http -sidebarTitle: http ---- - -# `fastmcp.server.http` - -## Functions - -### `set_http_request` - -```python -set_http_request(request: Request) -> Generator[Request, None, None] -``` - -### `create_base_app` - -```python -create_base_app(routes: list[BaseRoute], middleware: list[Middleware], debug: bool = False, lifespan: Callable | None = None) -> StarletteWithLifespan -``` - - -Create a base Starlette app with common middleware and routes. - -**Args:** -- `routes`: List of routes to include in the app -- `middleware`: List of middleware to include in the app -- `debug`: Whether to enable debug mode -- `lifespan`: Optional lifespan manager for the app - -**Returns:** -- A Starlette application - - -### `create_sse_app` - -```python -create_sse_app(server: FastMCP[LifespanResultT], message_path: str, sse_path: str, auth: AuthProvider | None = None, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan -``` - - -Return an instance of the SSE server app. - -**Args:** -- `server`: The FastMCP server instance -- `message_path`: Path for SSE messages -- `sse_path`: Path for SSE connections -- `auth`: Optional authentication provider (AuthProvider) -- `debug`: Whether to enable debug mode -- `routes`: Optional list of custom routes -- `middleware`: Optional list of middleware - -Returns: - A Starlette application with RequestContextMiddleware - - -### `create_streamable_http_app` - -```python -create_streamable_http_app(server: FastMCP[LifespanResultT], streamable_http_path: str, event_store: EventStore | None = None, retry_interval: int | None = None, auth: AuthProvider | None = None, json_response: bool = False, stateless_http: bool = False, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan -``` - - -Return an instance of the StreamableHTTP server app. - -**Args:** -- `server`: The FastMCP server instance -- `streamable_http_path`: Path for StreamableHTTP connections -- `event_store`: Optional event store for SSE polling/resumability -- `retry_interval`: Optional retry interval in milliseconds for SSE polling. -Controls how quickly clients should reconnect after server-initiated -disconnections. Requires event_store to be set. Defaults to SDK default. -- `auth`: Optional authentication provider (AuthProvider) -- `json_response`: Whether to use JSON response format -- `stateless_http`: Whether to use stateless mode (new transport per request) -- `debug`: Whether to enable debug mode -- `routes`: Optional list of custom routes -- `middleware`: Optional list of middleware - -**Returns:** -- A Starlette application with StreamableHTTP support - - -## Classes - -### `StreamableHTTPASGIApp` - - -ASGI application wrapper for Streamable HTTP server transport. - - -### `StarletteWithLifespan` - -**Methods:** - -#### `lifespan` - -```python -lifespan(self) -> Lifespan[Starlette] -``` - -### `RequestContextMiddleware` - - -Middleware that stores each request in a ContextVar and sets transport type. - diff --git a/docs/python-sdk/fastmcp-server-lifespan.mdx b/docs/python-sdk/fastmcp-server-lifespan.mdx deleted file mode 100644 index 08a67ddd9..000000000 --- a/docs/python-sdk/fastmcp-server-lifespan.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: lifespan -sidebarTitle: lifespan ---- - -# `fastmcp.server.lifespan` - - -Composable lifespans for FastMCP servers. - -This module provides a `@lifespan` decorator for creating composable server lifespans -that can be combined using the `|` operator. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.lifespan import lifespan - - @lifespan - async def db_lifespan(server): - conn = await connect_db() - yield {"db": conn} - await conn.close() - - @lifespan - async def cache_lifespan(server): - cache = await connect_cache() - yield {"cache": cache} - await cache.close() - - mcp = FastMCP("server", lifespan=db_lifespan | cache_lifespan) - ``` - -To compose with existing `@asynccontextmanager` lifespans, wrap them explicitly: - - ```python - from contextlib import asynccontextmanager - from fastmcp.server.lifespan import lifespan, ContextManagerLifespan - - @asynccontextmanager - async def legacy_lifespan(server): - yield {"legacy": True} - - @lifespan - async def new_lifespan(server): - yield {"new": True} - - # Wrap the legacy lifespan explicitly - combined = ContextManagerLifespan(legacy_lifespan) | new_lifespan - ``` - - -## Functions - -### `lifespan` - -```python -lifespan(fn: LifespanFn) -> Lifespan -``` - - -Decorator to create a composable lifespan. - -Use this decorator on an async generator function to make it composable -with other lifespans using the `|` operator. - -**Args:** -- `fn`: An async generator function that takes a FastMCP server and yields -a dict for the lifespan context. - -**Returns:** -- A composable Lifespan wrapper. - - -## Classes - -### `Lifespan` - - -Composable lifespan wrapper. - -Wraps an async generator function and enables composition via the `|` operator. -The wrapped function should yield a dict that becomes part of the lifespan context. - - -### `ContextManagerLifespan` - - -Lifespan wrapper for already-wrapped context manager functions. - -Use this for functions already decorated with @asynccontextmanager. - - -### `ComposedLifespan` - - -Two lifespans composed together. - -Enters the left lifespan first, then the right. Exits in reverse order. -Results are shallow-merged into a single dict. - diff --git a/docs/python-sdk/fastmcp-server-low_level.mdx b/docs/python-sdk/fastmcp-server-low_level.mdx deleted file mode 100644 index 9e188cf8c..000000000 --- a/docs/python-sdk/fastmcp-server-low_level.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: low_level -sidebarTitle: low_level ---- - -# `fastmcp.server.low_level` - -## Classes - -### `MiddlewareServerSession` - - -ServerSession that routes initialization requests through FastMCP middleware. - - -**Methods:** - -#### `fastmcp` - -```python -fastmcp(self) -> FastMCP -``` - -Get the FastMCP instance. - - -#### `client_supports_extension` - -```python -client_supports_extension(self, extension_id: str) -> bool -``` - -Check if the connected client supports a given MCP extension. - -Inspects the ``extensions`` extra field on ``ClientCapabilities`` -sent by the client during initialization. - - -### `LowLevelServer` - -**Methods:** - -#### `fastmcp` - -```python -fastmcp(self) -> FastMCP -``` - -Get the FastMCP instance. - - -#### `create_initialization_options` - -```python -create_initialization_options(self, notification_options: NotificationOptions | None = None, experimental_capabilities: dict[str, dict[str, Any]] | None = None, **kwargs: Any) -> InitializationOptions -``` - -#### `get_capabilities` - -```python -get_capabilities(self, notification_options: NotificationOptions, experimental_capabilities: dict[str, dict[str, Any]]) -> mcp.types.ServerCapabilities -``` - -Override to set capabilities.tasks as a first-class field per SEP-1686. - -This ensures task capabilities appear in capabilities.tasks instead of -capabilities.experimental.tasks, which is required by the MCP spec and -enables proper task detection by clients like VS Code Copilot 1.107+. - - -#### `run` - -```python -run(self, read_stream: MemoryObjectReceiveStream[SessionMessage | Exception], write_stream: MemoryObjectSendStream[SessionMessage], initialization_options: InitializationOptions, raise_exceptions: bool = False, stateless: bool = False) -``` - -Overrides the run method to use the MiddlewareServerSession. - - -#### `read_resource` - -```python -read_resource(self) -> Callable[[Callable[[AnyUrl], Awaitable[mcp.types.ReadResourceResult | mcp.types.CreateTaskResult]]], Callable[[AnyUrl], Awaitable[mcp.types.ReadResourceResult | mcp.types.CreateTaskResult]]] -``` - -Decorator for registering a read_resource handler with CreateTaskResult support. - -The MCP SDK's read_resource decorator does not support returning CreateTaskResult -for background task execution. This decorator wraps the result in ServerResult. - -This decorator can be removed once the MCP SDK adds native CreateTaskResult support -for resources. - - -#### `get_prompt` - -```python -get_prompt(self) -> Callable[[Callable[[str, dict[str, Any] | None], Awaitable[mcp.types.GetPromptResult | mcp.types.CreateTaskResult]]], Callable[[str, dict[str, Any] | None], Awaitable[mcp.types.GetPromptResult | mcp.types.CreateTaskResult]]] -``` - -Decorator for registering a get_prompt handler with CreateTaskResult support. - -The MCP SDK's get_prompt decorator does not support returning CreateTaskResult -for background task execution. This decorator wraps the result in ServerResult. - -This decorator can be removed once the MCP SDK adds native CreateTaskResult support -for prompts. - diff --git a/docs/python-sdk/fastmcp-server-middleware-__init__.mdx b/docs/python-sdk/fastmcp-server-middleware-__init__.mdx deleted file mode 100644 index 8583b1df9..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-__init__.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.middleware` - -*This module is empty or contains only private/internal implementations.* diff --git a/docs/python-sdk/fastmcp-server-middleware-authorization.mdx b/docs/python-sdk/fastmcp-server-middleware-authorization.mdx deleted file mode 100644 index 5bf859a09..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-authorization.mdx +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: authorization -sidebarTitle: authorization ---- - -# `fastmcp.server.middleware.authorization` - - -Authorization middleware for FastMCP. - -This module provides middleware-based authorization using callable auth checks. -AuthMiddleware applies auth checks globally to all components on the server. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.auth import require_scopes, restrict_tag - from fastmcp.server.middleware import AuthMiddleware - - # Require specific scope for all components - mcp = FastMCP(middleware=[ - AuthMiddleware(auth=require_scopes("api")) - ]) - - # Tag-based: components tagged "admin" require "admin" scope - mcp = FastMCP(middleware=[ - AuthMiddleware(auth=restrict_tag("admin", scopes=["admin"])) - ]) - ``` - - -## Classes - -### `AuthMiddleware` - - -Global authorization middleware using callable checks. - -This middleware applies auth checks to all components (tools, resources, -prompts) on the server. It uses the same callable API as component-level -auth checks. - -The middleware: -- Filters tools/resources/prompts from list responses based on auth checks -- Checks auth before tool execution, resource read, and prompt render -- Skips all auth checks for STDIO transport (no OAuth concept) - -**Args:** -- `auth`: A single auth check function or list of check functions. -All checks must pass for authorization to succeed (AND logic). - - -**Methods:** - -#### `on_list_tools` - -```python -on_list_tools(self, context: MiddlewareContext[mt.ListToolsRequest], call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]]) -> Sequence[Tool] -``` - -Filter tools/list response based on auth checks. - - -#### `on_call_tool` - -```python -on_call_tool(self, context: MiddlewareContext[mt.CallToolRequestParams], call_next: CallNext[mt.CallToolRequestParams, ToolResult]) -> ToolResult -``` - -Check auth before tool execution. - - -#### `on_list_resources` - -```python -on_list_resources(self, context: MiddlewareContext[mt.ListResourcesRequest], call_next: CallNext[mt.ListResourcesRequest, Sequence[Resource]]) -> Sequence[Resource] -``` - -Filter resources/list response based on auth checks. - - -#### `on_read_resource` - -```python -on_read_resource(self, context: MiddlewareContext[mt.ReadResourceRequestParams], call_next: CallNext[mt.ReadResourceRequestParams, ResourceResult]) -> ResourceResult -``` - -Check auth before resource read. - - -#### `on_list_resource_templates` - -```python -on_list_resource_templates(self, context: MiddlewareContext[mt.ListResourceTemplatesRequest], call_next: CallNext[mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate]]) -> Sequence[ResourceTemplate] -``` - -Filter resource templates/list response based on auth checks. - - -#### `on_list_prompts` - -```python -on_list_prompts(self, context: MiddlewareContext[mt.ListPromptsRequest], call_next: CallNext[mt.ListPromptsRequest, Sequence[Prompt]]) -> Sequence[Prompt] -``` - -Filter prompts/list response based on auth checks. - - -#### `on_get_prompt` - -```python -on_get_prompt(self, context: MiddlewareContext[mt.GetPromptRequestParams], call_next: CallNext[mt.GetPromptRequestParams, PromptResult]) -> PromptResult -``` - -Check auth before prompt render. - diff --git a/docs/python-sdk/fastmcp-server-middleware-caching.mdx b/docs/python-sdk/fastmcp-server-middleware-caching.mdx deleted file mode 100644 index 28a6eefc5..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-caching.mdx +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: caching -sidebarTitle: caching ---- - -# `fastmcp.server.middleware.caching` - - -A middleware for response caching. - -## Classes - -### `CachableResourceContent` - - -A wrapper for ResourceContent that can be cached. - - -### `CachableResourceResult` - - -A wrapper for ResourceResult that can be cached. - - -**Methods:** - -#### `get_size` - -```python -get_size(self) -> int -``` - -#### `wrap` - -```python -wrap(cls, value: ResourceResult) -> Self -``` - -#### `unwrap` - -```python -unwrap(self) -> ResourceResult -``` - -### `CachableToolResult` - -**Methods:** - -#### `wrap` - -```python -wrap(cls, value: ToolResult) -> Self -``` - -#### `unwrap` - -```python -unwrap(self) -> ToolResult -``` - -### `CachableMessage` - - -A wrapper for Message that can be cached. - - -### `CachablePromptResult` - - -A wrapper for PromptResult that can be cached. - - -**Methods:** - -#### `get_size` - -```python -get_size(self) -> int -``` - -#### `wrap` - -```python -wrap(cls, value: PromptResult) -> Self -``` - -#### `unwrap` - -```python -unwrap(self) -> PromptResult -``` - -### `SharedMethodSettings` - - -Shared config for a cache method. - - -### `ListToolsSettings` - - -Configuration options for Tool-related caching. - - -### `ListResourcesSettings` - - -Configuration options for Resource-related caching. - - -### `ListPromptsSettings` - - -Configuration options for Prompt-related caching. - - -### `CallToolSettings` - - -Configuration options for Tool-related caching. - - -### `ReadResourceSettings` - - -Configuration options for Resource-related caching. - - -### `GetPromptSettings` - - -Configuration options for Prompt-related caching. - - -### `ResponseCachingStatistics` - -### `ResponseCachingMiddleware` - - -The response caching middleware offers a simple way to cache responses to mcp methods. The Middleware -supports cache invalidation via notifications from the server. The Middleware implements TTL-based caching -but cache implementations may offer additional features like LRU eviction, size limits, and more. - -When items are retrieved from the cache they will no longer be the original objects, but rather no-op objects -this means that response caching may not be compatible with other middleware that expects original subclasses. - -Notes: -- Caches `tools/call`, `resources/read`, `prompts/get`, `tools/list`, `resources/list`, and `prompts/list` requests. -- Cache keys are derived from the method name, arguments, and the caller's - access token. Entries are partitioned per-token so that responses filtered - by per-component authorization (e.g. `auth=require_scopes(...)`) cannot - leak across users with different permissions. Unauthenticated callers - (including STDIO) share a single anonymous partition. - - -**Methods:** - -#### `on_list_tools` - -```python -on_list_tools(self, context: MiddlewareContext[mcp.types.ListToolsRequest], call_next: CallNext[mcp.types.ListToolsRequest, Sequence[Tool]]) -> Sequence[Tool] -``` - -List tools from the cache, if caching is enabled, and the result is in the cache. Otherwise, -otherwise call the next middleware and store the result in the cache if caching is enabled. - - -#### `on_list_resources` - -```python -on_list_resources(self, context: MiddlewareContext[mcp.types.ListResourcesRequest], call_next: CallNext[mcp.types.ListResourcesRequest, Sequence[Resource]]) -> Sequence[Resource] -``` - -List resources from the cache, if caching is enabled, and the result is in the cache. Otherwise, -otherwise call the next middleware and store the result in the cache if caching is enabled. - - -#### `on_list_prompts` - -```python -on_list_prompts(self, context: MiddlewareContext[mcp.types.ListPromptsRequest], call_next: CallNext[mcp.types.ListPromptsRequest, Sequence[Prompt]]) -> Sequence[Prompt] -``` - -List prompts from the cache, if caching is enabled, and the result is in the cache. Otherwise, -otherwise call the next middleware and store the result in the cache if caching is enabled. - - -#### `on_call_tool` - -```python -on_call_tool(self, context: MiddlewareContext[mcp.types.CallToolRequestParams], call_next: CallNext[mcp.types.CallToolRequestParams, ToolResult]) -> ToolResult -``` - -Call a tool from the cache, if caching is enabled, and the result is in the cache. Otherwise, -otherwise call the next middleware and store the result in the cache if caching is enabled. - - -#### `on_read_resource` - -```python -on_read_resource(self, context: MiddlewareContext[mcp.types.ReadResourceRequestParams], call_next: CallNext[mcp.types.ReadResourceRequestParams, ResourceResult]) -> ResourceResult -``` - -Read a resource from the cache, if caching is enabled, and the result is in the cache. Otherwise, -otherwise call the next middleware and store the result in the cache if caching is enabled. - - -#### `on_get_prompt` - -```python -on_get_prompt(self, context: MiddlewareContext[mcp.types.GetPromptRequestParams], call_next: CallNext[mcp.types.GetPromptRequestParams, PromptResult]) -> PromptResult -``` - -Get a prompt from the cache, if caching is enabled, and the result is in the cache. Otherwise, -otherwise call the next middleware and store the result in the cache if caching is enabled. - - -#### `statistics` - -```python -statistics(self) -> ResponseCachingStatistics -``` - -Get the statistics for the cache. - diff --git a/docs/python-sdk/fastmcp-server-middleware-dereference.mdx b/docs/python-sdk/fastmcp-server-middleware-dereference.mdx deleted file mode 100644 index 57c5edf88..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-dereference.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: dereference -sidebarTitle: dereference ---- - -# `fastmcp.server.middleware.dereference` - - -Middleware that dereferences $ref in JSON schemas before sending to clients. - -## Classes - -### `DereferenceRefsMiddleware` - - -Dereferences $ref in component schemas before sending to clients. - -Some MCP clients (e.g., VS Code Copilot) don't handle JSON Schema $ref -properly. This middleware inlines all $ref definitions so schemas are -self-contained. Enabled by default via ``FastMCP(dereference_schemas=True)``. - - -**Methods:** - -#### `on_list_tools` - -```python -on_list_tools(self, context: MiddlewareContext[mt.ListToolsRequest], call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]]) -> Sequence[Tool] -``` - -#### `on_list_resource_templates` - -```python -on_list_resource_templates(self, context: MiddlewareContext[mt.ListResourceTemplatesRequest], call_next: CallNext[mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate]]) -> Sequence[ResourceTemplate] -``` diff --git a/docs/python-sdk/fastmcp-server-middleware-error_handling.mdx b/docs/python-sdk/fastmcp-server-middleware-error_handling.mdx deleted file mode 100644 index d60c2468b..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-error_handling.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: error_handling -sidebarTitle: error_handling ---- - -# `fastmcp.server.middleware.error_handling` - - -Error handling middleware for consistent error responses and tracking. - -## Classes - -### `ErrorHandlingMiddleware` - - -Middleware that provides consistent error handling and logging. - -Catches exceptions, logs them appropriately, and converts them to -proper MCP error responses. Also tracks error patterns for monitoring. - - -**Methods:** - -#### `on_message` - -```python -on_message(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Handle errors for all messages. - - -#### `get_error_stats` - -```python -get_error_stats(self) -> dict[str, int] -``` - -Get error statistics for monitoring. - - -### `RetryMiddleware` - - -Middleware that implements automatic retry logic for failed requests. - -Retries requests that fail with transient errors, using exponential -backoff to avoid overwhelming the server or external dependencies. - - -**Methods:** - -#### `on_request` - -```python -on_request(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Implement retry logic for requests. - diff --git a/docs/python-sdk/fastmcp-server-middleware-logging.mdx b/docs/python-sdk/fastmcp-server-middleware-logging.mdx deleted file mode 100644 index 10f6933a1..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-logging.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: logging -sidebarTitle: logging ---- - -# `fastmcp.server.middleware.logging` - - -Comprehensive logging middleware for FastMCP servers. - -## Functions - -### `default_serializer` - -```python -default_serializer(data: Any) -> str -``` - - -The default serializer for Payloads in the logging middleware. - - -## Classes - -### `BaseLoggingMiddleware` - - -Base class for logging middleware. - - -**Methods:** - -#### `on_message` - -```python -on_message(self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]) -> Any -``` - -Log messages for configured methods. - - -### `LoggingMiddleware` - - -Middleware that provides comprehensive request and response logging. - -Logs all MCP messages with configurable detail levels. Useful for debugging, -monitoring, and understanding server usage patterns. - - -### `StructuredLoggingMiddleware` - - -Middleware that provides structured JSON logging for better log analysis. - -Outputs structured logs that are easier to parse and analyze with log -aggregation tools like ELK stack, Splunk, or cloud logging services. - diff --git a/docs/python-sdk/fastmcp-server-middleware-middleware.mdx b/docs/python-sdk/fastmcp-server-middleware-middleware.mdx deleted file mode 100644 index 04a87f554..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-middleware.mdx +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: middleware -sidebarTitle: middleware ---- - -# `fastmcp.server.middleware.middleware` - -## Functions - -### `make_middleware_wrapper` - -```python -make_middleware_wrapper(middleware: Middleware, call_next: CallNext[T, R]) -> CallNext[T, R] -``` - - -Create a wrapper that applies a single middleware to a context. The -closure bakes in the middleware and call_next function, so it can be -passed to other functions that expect a call_next function. - - -## Classes - -### `CallNext` - -### `MiddlewareContext` - - -Unified context for all middleware operations. - - -**Methods:** - -#### `copy` - -```python -copy(self, **kwargs: Any) -> MiddlewareContext[T] -``` - -### `Middleware` - - -Base class for FastMCP middleware with dispatching hooks. - - -**Methods:** - -#### `on_message` - -```python -on_message(self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]) -> Any -``` - -#### `on_request` - -```python -on_request(self, context: MiddlewareContext[mt.Request[Any, Any]], call_next: CallNext[mt.Request[Any, Any], Any]) -> Any -``` - -#### `on_notification` - -```python -on_notification(self, context: MiddlewareContext[mt.Notification[Any, Any]], call_next: CallNext[mt.Notification[Any, Any], Any]) -> Any -``` - -#### `on_initialize` - -```python -on_initialize(self, context: MiddlewareContext[mt.InitializeRequest], call_next: CallNext[mt.InitializeRequest, mt.InitializeResult | None]) -> mt.InitializeResult | None -``` - -#### `on_call_tool` - -```python -on_call_tool(self, context: MiddlewareContext[mt.CallToolRequestParams], call_next: CallNext[mt.CallToolRequestParams, ToolResult]) -> ToolResult -``` - -#### `on_read_resource` - -```python -on_read_resource(self, context: MiddlewareContext[mt.ReadResourceRequestParams], call_next: CallNext[mt.ReadResourceRequestParams, ResourceResult]) -> ResourceResult -``` - -#### `on_get_prompt` - -```python -on_get_prompt(self, context: MiddlewareContext[mt.GetPromptRequestParams], call_next: CallNext[mt.GetPromptRequestParams, PromptResult]) -> PromptResult -``` - -#### `on_list_tools` - -```python -on_list_tools(self, context: MiddlewareContext[mt.ListToolsRequest], call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]]) -> Sequence[Tool] -``` - -#### `on_list_resources` - -```python -on_list_resources(self, context: MiddlewareContext[mt.ListResourcesRequest], call_next: CallNext[mt.ListResourcesRequest, Sequence[Resource]]) -> Sequence[Resource] -``` - -#### `on_list_resource_templates` - -```python -on_list_resource_templates(self, context: MiddlewareContext[mt.ListResourceTemplatesRequest], call_next: CallNext[mt.ListResourceTemplatesRequest, Sequence[ResourceTemplate]]) -> Sequence[ResourceTemplate] -``` - -#### `on_list_prompts` - -```python -on_list_prompts(self, context: MiddlewareContext[mt.ListPromptsRequest], call_next: CallNext[mt.ListPromptsRequest, Sequence[Prompt]]) -> Sequence[Prompt] -``` diff --git a/docs/python-sdk/fastmcp-server-middleware-ping.mdx b/docs/python-sdk/fastmcp-server-middleware-ping.mdx deleted file mode 100644 index 7ff39d339..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-ping.mdx +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: ping -sidebarTitle: ping ---- - -# `fastmcp.server.middleware.ping` - - -Ping middleware for keeping client connections alive. - -## Classes - -### `PingMiddleware` - - -Middleware that sends periodic pings to keep client connections alive. - -Starts a background ping task on first message from each session. The task -sends server-to-client pings at the configured interval until the session -ends. - - -**Methods:** - -#### `on_message` - -```python -on_message(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Start ping task on first message from a session. - diff --git a/docs/python-sdk/fastmcp-server-middleware-rate_limiting.mdx b/docs/python-sdk/fastmcp-server-middleware-rate_limiting.mdx deleted file mode 100644 index 0ac2c263f..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-rate_limiting.mdx +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: rate_limiting -sidebarTitle: rate_limiting ---- - -# `fastmcp.server.middleware.rate_limiting` - - -Rate limiting middleware for protecting FastMCP servers from abuse. - -## Classes - -### `RateLimitError` - - -Error raised when rate limit is exceeded. - - -### `TokenBucketRateLimiter` - - -Token bucket implementation for rate limiting. - - -**Methods:** - -#### `consume` - -```python -consume(self, tokens: int = 1) -> bool -``` - -Try to consume tokens from the bucket. - -**Args:** -- `tokens`: Number of tokens to consume - -**Returns:** -- True if tokens were available and consumed, False otherwise - - -### `SlidingWindowRateLimiter` - - -Sliding window rate limiter implementation. - - -**Methods:** - -#### `is_allowed` - -```python -is_allowed(self) -> bool -``` - -Check if a request is allowed. - - -### `RateLimitingMiddleware` - - -Middleware that implements rate limiting to prevent server abuse. - -Uses a token bucket algorithm by default, allowing for burst traffic -while maintaining a sustainable long-term rate. - - -**Methods:** - -#### `on_request` - -```python -on_request(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Apply rate limiting to requests. - - -### `SlidingWindowRateLimitingMiddleware` - - -Middleware that implements sliding window rate limiting. - -Uses a sliding window approach which provides more precise rate limiting -but uses more memory to track individual request timestamps. - - -**Methods:** - -#### `on_request` - -```python -on_request(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Apply sliding window rate limiting to requests. - diff --git a/docs/python-sdk/fastmcp-server-middleware-response_limiting.mdx b/docs/python-sdk/fastmcp-server-middleware-response_limiting.mdx deleted file mode 100644 index b897f16c3..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-response_limiting.mdx +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: response_limiting -sidebarTitle: response_limiting ---- - -# `fastmcp.server.middleware.response_limiting` - - -Response limiting middleware for controlling tool response sizes. - -## Classes - -### `ResponseLimitingMiddleware` - - -Middleware that limits the response size of tool calls. - -Intercepts tool call responses and enforces size limits. If a response -exceeds the limit, it extracts text content, truncates it, and returns -a single TextContent block. - - -**Methods:** - -#### `on_call_tool` - -```python -on_call_tool(self, context: MiddlewareContext[mt.CallToolRequestParams], call_next: CallNext[mt.CallToolRequestParams, ToolResult]) -> ToolResult -``` - -Intercept tool calls and limit response size. - diff --git a/docs/python-sdk/fastmcp-server-middleware-timing.mdx b/docs/python-sdk/fastmcp-server-middleware-timing.mdx deleted file mode 100644 index 533ff5de8..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-timing.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: timing -sidebarTitle: timing ---- - -# `fastmcp.server.middleware.timing` - - -Timing middleware for measuring and logging request performance. - -## Classes - -### `TimingMiddleware` - - -Middleware that logs the execution time of requests. - -Only measures and logs timing for request messages (not notifications). -Provides insights into performance characteristics of your MCP server. - - -**Methods:** - -#### `on_request` - -```python -on_request(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time request execution and log the results. - - -### `DetailedTimingMiddleware` - - -Enhanced timing middleware with per-operation breakdowns. - -Provides detailed timing information for different types of MCP operations, -allowing you to identify performance bottlenecks in specific operations. - - -**Methods:** - -#### `on_call_tool` - -```python -on_call_tool(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time tool execution. - - -#### `on_read_resource` - -```python -on_read_resource(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time resource reading. - - -#### `on_get_prompt` - -```python -on_get_prompt(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time prompt retrieval. - - -#### `on_list_tools` - -```python -on_list_tools(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time tool listing. - - -#### `on_list_resources` - -```python -on_list_resources(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time resource listing. - - -#### `on_list_resource_templates` - -```python -on_list_resource_templates(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time resource template listing. - - -#### `on_list_prompts` - -```python -on_list_prompts(self, context: MiddlewareContext, call_next: CallNext) -> Any -``` - -Time prompt listing. - diff --git a/docs/python-sdk/fastmcp-server-middleware-tool_injection.mdx b/docs/python-sdk/fastmcp-server-middleware-tool_injection.mdx deleted file mode 100644 index 549150689..000000000 --- a/docs/python-sdk/fastmcp-server-middleware-tool_injection.mdx +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: tool_injection -sidebarTitle: tool_injection ---- - -# `fastmcp.server.middleware.tool_injection` - - -A middleware for injecting tools into the MCP server context. - -## Functions - -### `list_prompts` - -```python -list_prompts(context: Context) -> list[Prompt] -``` - - -List prompts available on the server. - - -### `get_prompt` - -```python -get_prompt(context: Context, name: Annotated[str, 'The name of the prompt to render.'], arguments: Annotated[dict[str, Any] | None, 'The arguments to pass to the prompt.'] = None) -> mcp.types.GetPromptResult -``` - - -Render a prompt available on the server. - - -### `list_resources` - -```python -list_resources(context: Context) -> list[mcp.types.Resource] -``` - - -List resources available on the server. - - -### `read_resource` - -```python -read_resource(context: Context, uri: Annotated[AnyUrl | str, 'The URI of the resource to read.']) -> ResourceResult -``` - - -Read a resource available on the server. - - -## Classes - -### `ToolInjectionMiddleware` - - -A middleware for injecting tools into the context. - - -**Methods:** - -#### `on_list_tools` - -```python -on_list_tools(self, context: MiddlewareContext[mcp.types.ListToolsRequest], call_next: CallNext[mcp.types.ListToolsRequest, Sequence[Tool]]) -> Sequence[Tool] -``` - -Inject tools into the response. - - -#### `on_call_tool` - -```python -on_call_tool(self, context: MiddlewareContext[mcp.types.CallToolRequestParams], call_next: CallNext[mcp.types.CallToolRequestParams, ToolResult]) -> ToolResult -``` - -Intercept tool calls to injected tools. - - -### `PromptToolMiddleware` - - -A middleware for injecting prompts as tools into the context. - -.. deprecated:: - Use ``fastmcp.server.transforms.PromptsAsTools`` instead. - - -### `ResourceToolMiddleware` - - -A middleware for injecting resources as tools into the context. - -.. deprecated:: - Use ``fastmcp.server.transforms.ResourcesAsTools`` instead. - diff --git a/docs/python-sdk/fastmcp-server-mixins-__init__.mdx b/docs/python-sdk/fastmcp-server-mixins-__init__.mdx deleted file mode 100644 index d35f9fc06..000000000 --- a/docs/python-sdk/fastmcp-server-mixins-__init__.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.mixins` - - -Server mixins for FastMCP. diff --git a/docs/python-sdk/fastmcp-server-mixins-lifespan.mdx b/docs/python-sdk/fastmcp-server-mixins-lifespan.mdx deleted file mode 100644 index fe786652c..000000000 --- a/docs/python-sdk/fastmcp-server-mixins-lifespan.mdx +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: lifespan -sidebarTitle: lifespan ---- - -# `fastmcp.server.mixins.lifespan` - - -Lifespan and Docket task infrastructure for FastMCP Server. - -## Classes - -### `LifespanMixin` - - -Mixin providing lifespan and Docket task infrastructure for FastMCP. - - -**Methods:** - -#### `docket` - -```python -docket(self: FastMCP) -> Docket | None -``` - -Get the Docket instance if Docket support is enabled. - -Returns None if Docket is not enabled or server hasn't been started yet. - diff --git a/docs/python-sdk/fastmcp-server-mixins-mcp_operations.mdx b/docs/python-sdk/fastmcp-server-mixins-mcp_operations.mdx deleted file mode 100644 index 6fbd2855a..000000000 --- a/docs/python-sdk/fastmcp-server-mixins-mcp_operations.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: mcp_operations -sidebarTitle: mcp_operations ---- - -# `fastmcp.server.mixins.mcp_operations` - - -MCP protocol handler setup and wire-format handlers for FastMCP Server. - -## Classes - -### `MCPOperationsMixin` - - -Mixin providing MCP protocol handler setup and wire-format handlers. - -Note: Methods registered with SDK decorators (e.g., _list_tools_mcp, _call_tool_mcp) -cannot use `self: FastMCP` type hints because the SDK's `get_type_hints()` fails -to resolve FastMCP at runtime (it's only available under TYPE_CHECKING). When -type hints fail to resolve, the SDK falls back to calling handlers with no arguments. -These methods use untyped `self` to avoid this issue. - diff --git a/docs/python-sdk/fastmcp-server-mixins-transport.mdx b/docs/python-sdk/fastmcp-server-mixins-transport.mdx deleted file mode 100644 index 0d29ed280..000000000 --- a/docs/python-sdk/fastmcp-server-mixins-transport.mdx +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: transport -sidebarTitle: transport ---- - -# `fastmcp.server.mixins.transport` - - -Transport-related methods for FastMCP Server. - -## Classes - -### `TransportMixin` - - -Mixin providing transport-related methods for FastMCP. - -Includes HTTP/stdio/SSE transport handling and custom HTTP routes. - - -**Methods:** - -#### `run_async` - -```python -run_async(self: FastMCP, transport: Transport | None = None, show_banner: bool | None = None, **transport_kwargs: Any) -> None -``` - -Run the FastMCP server asynchronously. - -**Args:** -- `transport`: Transport protocol to use ("stdio", "http", "sse", or "streamable-http") -- `show_banner`: Whether to display the server banner. If None, uses the -FASTMCP_SHOW_SERVER_BANNER setting (default\: True). - - -#### `run` - -```python -run(self: FastMCP, transport: Transport | None = None, show_banner: bool | None = None, **transport_kwargs: Any) -> None -``` - -Run the FastMCP server. Note this is a synchronous function. - -**Args:** -- `transport`: Transport protocol to use ("http", "stdio", "sse", or "streamable-http") -- `show_banner`: Whether to display the server banner. If None, uses the -FASTMCP_SHOW_SERVER_BANNER setting (default\: True). - - -#### `custom_route` - -```python -custom_route(self: FastMCP, path: str, methods: list[str], name: str | None = None, include_in_schema: bool = True) -> Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]] -``` - -Decorator to register a custom HTTP route on the FastMCP server. - -Allows adding arbitrary HTTP endpoints outside the standard MCP protocol, -which can be useful for OAuth callbacks, health checks, or admin APIs. -The handler function must be an async function that accepts a Starlette -Request and returns a Response. - -**Args:** -- `path`: URL path for the route (e.g., "/auth/callback") -- `methods`: List of HTTP methods to support (e.g., ["GET", "POST"]) -- `name`: Optional name for the route (to reference this route with -Starlette's reverse URL lookup feature) -- `include_in_schema`: Whether to include in OpenAPI schema, defaults to True - - -#### `run_stdio_async` - -```python -run_stdio_async(self: FastMCP, show_banner: bool = True, log_level: str | None = None, stateless: bool = False) -> None -``` - -Run the server using stdio transport. - -**Args:** -- `show_banner`: Whether to display the server banner -- `log_level`: Log level for the server -- `stateless`: Whether to run in stateless mode (no session initialization) - - -#### `run_http_async` - -```python -run_http_async(self: FastMCP, show_banner: bool = True, transport: Literal['http', 'streamable-http', 'sse'] = 'http', host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, stateless: bool | None = None) -> None -``` - -Run the server using HTTP transport. - -**Args:** -- `transport`: Transport protocol to use - "http" (default), "streamable-http", or "sse" -- `host`: Host address to bind to (defaults to settings.host) -- `port`: Port to bind to (defaults to settings.port) -- `log_level`: Log level for the server (defaults to settings.log_level) -- `path`: Path for the endpoint (defaults to settings.streamable_http_path or settings.sse_path) -- `uvicorn_config`: Additional configuration for the Uvicorn server -- `middleware`: A list of middleware to apply to the app -- `json_response`: Whether to use JSON response format (defaults to settings.json_response) -- `stateless_http`: Whether to use stateless HTTP (defaults to settings.stateless_http) -- `stateless`: Alias for stateless_http for CLI consistency - - -#### `http_app` - -```python -http_app(self: FastMCP, path: str | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http', event_store: EventStore | None = None, retry_interval: int | None = None) -> StarletteWithLifespan -``` - -Create a Starlette app using the specified HTTP transport. - -**Args:** -- `path`: The path for the HTTP endpoint -- `middleware`: A list of middleware to apply to the app -- `json_response`: Whether to use JSON response format -- `stateless_http`: Whether to use stateless mode (new transport per request) -- `transport`: Transport protocol to use - "http", "streamable-http", or "sse" -- `event_store`: Optional event store for SSE polling/resumability. When set, -enables clients to reconnect and resume receiving events after -server-initiated disconnections. Only used with streamable-http transport. -- `retry_interval`: Optional retry interval in milliseconds for SSE polling. -Controls how quickly clients should reconnect after server-initiated -disconnections. Requires event_store to be set. Only used with -streamable-http transport. - -**Returns:** -- A Starlette application configured with the specified transport - diff --git a/docs/python-sdk/fastmcp-server-openapi-__init__.mdx b/docs/python-sdk/fastmcp-server-openapi-__init__.mdx deleted file mode 100644 index af9cd5517..000000000 --- a/docs/python-sdk/fastmcp-server-openapi-__init__.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.openapi` - - -OpenAPI server implementation for FastMCP. - -.. deprecated:: - This module is deprecated. Import from fastmcp.server.providers.openapi instead. - -The recommended approach is to use OpenAPIProvider with FastMCP: - - from fastmcp import FastMCP - from fastmcp.server.providers.openapi import OpenAPIProvider - import httpx - - client = httpx.AsyncClient(base_url="https://api.example.com") - provider = OpenAPIProvider(openapi_spec=spec, client=client) - - mcp = FastMCP("My API Server") - mcp.add_provider(provider) - -FastMCPOpenAPI is still available but deprecated. - diff --git a/docs/python-sdk/fastmcp-server-openapi-components.mdx b/docs/python-sdk/fastmcp-server-openapi-components.mdx deleted file mode 100644 index 320cc7092..000000000 --- a/docs/python-sdk/fastmcp-server-openapi-components.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: components -sidebarTitle: components ---- - -# `fastmcp.server.openapi.components` - - -OpenAPI component implementations - backwards compatibility stub. - -This module is deprecated. Import from fastmcp.server.providers.openapi instead. - diff --git a/docs/python-sdk/fastmcp-server-openapi-routing.mdx b/docs/python-sdk/fastmcp-server-openapi-routing.mdx deleted file mode 100644 index 650a4a497..000000000 --- a/docs/python-sdk/fastmcp-server-openapi-routing.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: routing -sidebarTitle: routing ---- - -# `fastmcp.server.openapi.routing` - - -Route mapping logic for OpenAPI operations. - -.. deprecated:: - This module is deprecated. Import from fastmcp.server.providers.openapi instead. - diff --git a/docs/python-sdk/fastmcp-server-openapi-server.mdx b/docs/python-sdk/fastmcp-server-openapi-server.mdx deleted file mode 100644 index 374eac2ba..000000000 --- a/docs/python-sdk/fastmcp-server-openapi-server.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: server -sidebarTitle: server ---- - -# `fastmcp.server.openapi.server` - - -FastMCPOpenAPI - backwards compatibility wrapper. - -This class is deprecated. Use FastMCP with OpenAPIProvider instead: - - from fastmcp import FastMCP - from fastmcp.server.providers.openapi import OpenAPIProvider - import httpx - - client = httpx.AsyncClient(base_url="https://api.example.com") - provider = OpenAPIProvider(openapi_spec=spec, client=client) - mcp = FastMCP("My API Server", providers=[provider]) - - -## Classes - -### `FastMCPOpenAPI` - - -FastMCP server implementation that creates components from an OpenAPI schema. - -.. deprecated:: - Use FastMCP with OpenAPIProvider instead. This class will be - removed in a future version. - -Example (deprecated): - ```python - from fastmcp.server.openapi import FastMCPOpenAPI - import httpx - - server = FastMCPOpenAPI( - openapi_spec=spec, - client=httpx.AsyncClient(), - ) - ``` - diff --git a/docs/python-sdk/fastmcp-server-providers-__init__.mdx b/docs/python-sdk/fastmcp-server-providers-__init__.mdx deleted file mode 100644 index b7addb653..000000000 --- a/docs/python-sdk/fastmcp-server-providers-__init__.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.providers` - - -Providers for dynamic MCP components. - -This module provides the `Provider` abstraction for providing tools, -resources, and prompts dynamically at runtime. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.providers import Provider - from fastmcp.tools import Tool - - class DatabaseProvider(Provider): - def __init__(self, db_url: str): - self.db = Database(db_url) - - async def _list_tools(self) -> list[Tool]: - rows = await self.db.fetch("SELECT * FROM tools") - return [self._make_tool(row) for row in rows] - - async def _get_tool(self, name: str) -> Tool | None: - row = await self.db.fetchone("SELECT * FROM tools WHERE name = ?", name) - return self._make_tool(row) if row else None - - mcp = FastMCP("Server", providers=[DatabaseProvider(db_url)]) - ``` - diff --git a/docs/python-sdk/fastmcp-server-providers-addressing.mdx b/docs/python-sdk/fastmcp-server-providers-addressing.mdx deleted file mode 100644 index 48b953e87..000000000 --- a/docs/python-sdk/fastmcp-server-providers-addressing.mdx +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: addressing -sidebarTitle: addressing ---- - -# `fastmcp.server.providers.addressing` - - -Deterministic tool hashing for backend-tool routing and per-tool resources. - -Each FastMCPApp backend tool gets a deterministic hash computed from its -app name + tool name. The hash serves two purposes: - -1. **Backend-tool routing.** Tools with ``"app"`` in their visibility are - callable via ``_``. The dispatcher parses the prefix, - then walks providers recursively (same pattern as the old ``get_app_tool``) - to find a tool whose stored hash matches. - -2. **Per-tool Prefab renderer URIs.** Each prefab tool gets a unique renderer - resource at ``ui://prefab/tool//renderer.html``. ``list_resources`` - and ``read_resource`` synthesize these on demand from the tool's meta. - -The hash is computed at registration time from ``(app_name, tool_name)`` — -both known at that moment — and stored in ``meta["fastmcp"]["_tool_hash"]``. -Deterministic across replicas (same code → same hash), no registry walk -needed. - - -## Functions - -### `hash_tool` - -```python -hash_tool(app_name: str, tool_name: str) -> str -``` - - -Deterministic hex hash for a tool in an app. - -Same inputs on every replica produce the same output. - - -### `hashed_backend_name` - -```python -hashed_backend_name(app_name: str, tool_name: str) -> str -``` - - -Format the universal name for a backend tool: ``_``. - - -### `parse_hashed_backend_name` - -```python -parse_hashed_backend_name(name: str) -> tuple[str, str] | None -``` - - -Parse ``_`` → ``(hash, local_tool_name)`` or None. - - -### `hashed_resource_uri` - -```python -hashed_resource_uri(app_name: str, tool_name: str) -> str -``` - - -Per-tool Prefab renderer resource URI. - - -### `parse_hashed_resource_uri` - -```python -parse_hashed_resource_uri(uri: str) -> str | None -``` - - -Extract the hash from a Prefab renderer URI, or None. - diff --git a/docs/python-sdk/fastmcp-server-providers-aggregate.mdx b/docs/python-sdk/fastmcp-server-providers-aggregate.mdx deleted file mode 100644 index 36feac09c..000000000 --- a/docs/python-sdk/fastmcp-server-providers-aggregate.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: aggregate -sidebarTitle: aggregate ---- - -# `fastmcp.server.providers.aggregate` - - -AggregateProvider for combining multiple providers into one. - -This module provides `AggregateProvider`, a utility class that presents -multiple providers as a single unified provider. Useful when you want to -combine custom providers without creating a full FastMCP server. - -Example: - ```python - from fastmcp.server.providers import AggregateProvider - - # Combine multiple providers into one - combined = AggregateProvider() - combined.add_provider(provider1) - combined.add_provider(provider2, namespace="api") # Tools become "api_foo" - - # Use like any other provider - tools = await combined.list_tools() - ``` - - -## Classes - -### `AggregateProvider` - - -Utility provider that combines multiple providers into one. - -Components are aggregated from all providers. For get_* operations, -providers are queried in parallel and the highest version is returned. - -When adding providers with a namespace, wrap_transform() is used to apply -the Namespace transform. This means namespace transformation is handled -by the wrapped provider, not by AggregateProvider. - -Errors from individual providers are logged and skipped (graceful degradation). - - -**Methods:** - -#### `add_provider` - -```python -add_provider(self, provider: Provider) -> None -``` - -Add a provider with optional namespace. - -If the provider is a FastMCP server, it's automatically wrapped in -FastMCPProvider to ensure middleware is invoked correctly. - -**Args:** -- `provider`: The provider to add. -- `namespace`: Optional namespace prefix. When set\: -- Tools become "namespace_toolname" -- Resources become "protocol\://namespace/path" -- Prompts become "namespace_promptname" - - -#### `get_app_tool` - -```python -get_app_tool(self, app_name: str, tool_name: str) -> Tool | None -``` - -Query all child providers for an app tool. - - -#### `get_tool_by_hash` - -```python -get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None -``` - -Query all child providers for a tool matching a hash. - - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Get all task-eligible components from all providers. - - -#### `lifespan` - -```python -lifespan(self) -> AsyncIterator[None] -``` - -Combine lifespans of all providers. - diff --git a/docs/python-sdk/fastmcp-server-providers-base.mdx b/docs/python-sdk/fastmcp-server-providers-base.mdx deleted file mode 100644 index 6d4774977..000000000 --- a/docs/python-sdk/fastmcp-server-providers-base.mdx +++ /dev/null @@ -1,334 +0,0 @@ ---- -title: base -sidebarTitle: base ---- - -# `fastmcp.server.providers.base` - - -Base Provider class for dynamic MCP components. - -This module provides the `Provider` abstraction for providing tools, -resources, and prompts dynamically at runtime. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.providers import Provider - from fastmcp.tools import Tool - - class DatabaseProvider(Provider): - def __init__(self, db_url: str): - super().__init__() - self.db = Database(db_url) - - async def _list_tools(self) -> list[Tool]: - rows = await self.db.fetch("SELECT * FROM tools") - return [self._make_tool(row) for row in rows] - - async def _get_tool(self, name: str) -> Tool | None: - row = await self.db.fetchone("SELECT * FROM tools WHERE name = ?", name) - return self._make_tool(row) if row else None - - mcp = FastMCP("Server", providers=[DatabaseProvider(db_url)]) - ``` - - -## Classes - -### `Provider` - - -Base class for dynamic component providers. - -Subclass and override whichever methods you need. Default implementations -return empty lists / None, so you only need to implement what your provider -supports. - - -**Methods:** - -#### `transforms` - -```python -transforms(self) -> list[Transform] -``` - -All transforms applied to components from this provider. - - -#### `add_transform` - -```python -add_transform(self, transform: Transform) -> None -``` - -Add a transform to this provider. - -Transforms modify components (tools, resources, prompts) as they flow -through the provider. They're applied in order - first added is innermost. - -**Args:** -- `transform`: The transform to add. - - -#### `wrap_transform` - -```python -wrap_transform(self, transform: Transform) -> Provider -``` - -Return a new provider with this transform applied (immutable). - -Unlike add_transform() which mutates this provider, wrap_transform() -returns a new provider that wraps this one. The original provider -is unchanged. - -This is useful when you want to apply transforms without side effects, -such as adding the same provider to multiple aggregators with different -namespaces. - -**Args:** -- `transform`: The transform to apply. - -**Returns:** -- A new provider that wraps this one with the transform applied. - - -#### `list_tools` - -```python -list_tools(self) -> Sequence[Tool] -``` - -List tools with all transforms applied. - -Applies transforms sequentially: base → transforms (in order). -Each transform receives the result from the previous transform. -Components may be marked as disabled but are NOT filtered here - -filtering happens at the server level to allow session transforms to override. - -**Returns:** -- Transformed sequence of tools (including disabled ones). - - -#### `get_tool` - -```python -get_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None -``` - -Get tool by transformed name with all transforms applied. - -Note: This method does NOT filter disabled components. The Server -(FastMCP) performs enabled filtering after all transforms complete, -allowing session-level transforms to override provider-level disables. - -**Args:** -- `name`: The transformed tool name to look up. -- `version`: Optional version filter. If None, returns highest version. - -**Returns:** -- The tool if found (may be marked disabled), None if not found. - - -#### `get_app_tool` - -```python -get_app_tool(self, app_name: str, tool_name: str) -> Tool | None -``` - -Look up an app-visible tool by original name, bypassing transforms. - -Searches for a tool named ``tool_name`` tagged with the given app -name. Skips the transform chain entirely. - -**Returns:** -- The tool if found and tagged with the given app name, else None. - - -#### `get_tool_by_hash` - -```python -get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None -``` - -Look up an app-visible tool by its deterministic hash. - -Same recursive-walk semantics as ``get_app_tool`` but matches on -``meta["fastmcp"]["_tool_hash"]`` instead of the app name tag. -Used by the dispatcher when receiving hashed backend-tool calls. - - -#### `list_resources` - -```python -list_resources(self) -> Sequence[Resource] -``` - -List resources with all transforms applied. - -Components may be marked as disabled but are NOT filtered here. - - -#### `get_resource` - -```python -get_resource(self, uri: str, version: VersionSpec | None = None) -> Resource | None -``` - -Get resource by transformed URI with all transforms applied. - -Note: This method does NOT filter disabled components. The Server -(FastMCP) performs enabled filtering after all transforms complete. - -**Args:** -- `uri`: The transformed resource URI to look up. -- `version`: Optional version filter. If None, returns highest version. - -**Returns:** -- The resource if found (may be marked disabled), None if not found. - - -#### `list_resource_templates` - -```python -list_resource_templates(self) -> Sequence[ResourceTemplate] -``` - -List resource templates with all transforms applied. - -Components may be marked as disabled but are NOT filtered here. - - -#### `get_resource_template` - -```python -get_resource_template(self, uri: str, version: VersionSpec | None = None) -> ResourceTemplate | None -``` - -Get resource template by transformed URI with all transforms applied. - -Note: This method does NOT filter disabled components. The Server -(FastMCP) performs enabled filtering after all transforms complete. - -**Args:** -- `uri`: The transformed template URI to look up. -- `version`: Optional version filter. If None, returns highest version. - -**Returns:** -- The template if found (may be marked disabled), None if not found. - - -#### `list_prompts` - -```python -list_prompts(self) -> Sequence[Prompt] -``` - -List prompts with all transforms applied. - -Components may be marked as disabled but are NOT filtered here. - - -#### `get_prompt` - -```python -get_prompt(self, name: str, version: VersionSpec | None = None) -> Prompt | None -``` - -Get prompt by transformed name with all transforms applied. - -Note: This method does NOT filter disabled components. The Server -(FastMCP) performs enabled filtering after all transforms complete. - -**Args:** -- `name`: The transformed prompt name to look up. -- `version`: Optional version filter. If None, returns highest version. - -**Returns:** -- The prompt if found (may be marked disabled), None if not found. - - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Return components that should be registered as background tasks. - -Override to customize which components are task-eligible. -Default calls list_* methods, applies provider transforms, and filters -for components with task_config.mode != 'forbidden'. - -Used by the server during startup to register functions with Docket. - - -#### `lifespan` - -```python -lifespan(self) -> AsyncIterator[None] -``` - -User-overridable lifespan for custom setup and teardown. - -Override this method to perform provider-specific initialization -like opening database connections, setting up external resources, -or other state management needed for the provider's lifetime. - -The lifespan scope matches the server's lifespan - code before yield -runs at startup, code after yield runs at shutdown. - - -#### `enable` - -```python -enable(self) -> Self -``` - -Enable components matching all specified criteria. - -Adds a visibility transform that marks matching components as enabled. -Later transforms override earlier ones, so enable after disable makes -the component enabled. - -With only=True, switches to allowlist mode - first disables everything, -then enables matching components. - -**Args:** -- `names`: Component names or URIs to enable. -- `keys`: Component keys to enable (e.g., {"tool\:my_tool@v1"}). -- `version`: Component version spec to enable (e.g., VersionSpec(eq="v1") or -VersionSpec(gte="v2")). Unversioned components will not match. -- `tags`: Enable components with these tags. -- `components`: Component types to include (e.g., {"tool", "prompt"}). -- `only`: If True, ONLY enable matching components (allowlist mode). - -**Returns:** -- Self for method chaining. - - -#### `disable` - -```python -disable(self) -> Self -``` - -Disable components matching all specified criteria. - -Adds a visibility transform that marks matching components as disabled. -Components can be re-enabled by calling enable() with matching criteria -(the later transform wins). - -**Args:** -- `names`: Component names or URIs to disable. -- `keys`: Component keys to disable (e.g., {"tool\:my_tool@v1"}). -- `version`: Component version spec to disable (e.g., VersionSpec(eq="v1") or -VersionSpec(gte="v2")). Unversioned components will not match. -- `tags`: Disable components with these tags. -- `components`: Component types to include (e.g., {"tool", "prompt"}). - -**Returns:** -- Self for method chaining. - diff --git a/docs/python-sdk/fastmcp-server-providers-fastmcp_provider.mdx b/docs/python-sdk/fastmcp-server-providers-fastmcp_provider.mdx deleted file mode 100644 index 5be980e25..000000000 --- a/docs/python-sdk/fastmcp-server-providers-fastmcp_provider.mdx +++ /dev/null @@ -1,256 +0,0 @@ ---- -title: fastmcp_provider -sidebarTitle: fastmcp_provider ---- - -# `fastmcp.server.providers.fastmcp_provider` - - -FastMCPProvider for wrapping FastMCP servers as providers. - -This module provides the `FastMCPProvider` class that wraps a FastMCP server -and exposes its components through the Provider interface. - -It also provides FastMCPProvider* component classes that delegate execution to -the wrapped server's middleware, ensuring middleware runs when components are -executed. - - -## Classes - -### `FastMCPProviderTool` - - -Tool that delegates execution to a wrapped server's middleware. - -When `run()` is called, this tool invokes the wrapped server's -`_call_tool_middleware()` method, ensuring the server's middleware -chain is executed. - - -**Methods:** - -#### `wrap` - -```python -wrap(cls, server: Any, tool: Tool) -> FastMCPProviderTool -``` - -Wrap a Tool to delegate execution to the server's middleware. - - -#### `run` - -```python -run(self, arguments: dict[str, Any]) -> ToolResult -``` - -Delegate to child server's call_tool() without task_meta. - -This is called when the tool is used within a TransformedTool -forwarding function or other contexts where task_meta is not available. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `FastMCPProviderResource` - - -Resource that delegates reading to a wrapped server's read_resource(). - -When `read()` is called, this resource invokes the wrapped server's -`read_resource()` method, ensuring the server's middleware chain is executed. - - -**Methods:** - -#### `wrap` - -```python -wrap(cls, server: Any, resource: Resource) -> FastMCPProviderResource -``` - -Wrap a Resource to delegate reading to the server's middleware. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `FastMCPProviderPrompt` - - -Prompt that delegates rendering to a wrapped server's render_prompt(). - -When `render()` is called, this prompt invokes the wrapped server's -`render_prompt()` method, ensuring the server's middleware chain is executed. - - -**Methods:** - -#### `wrap` - -```python -wrap(cls, server: Any, prompt: Prompt) -> FastMCPProviderPrompt -``` - -Wrap a Prompt to delegate rendering to the server's middleware. - - -#### `render` - -```python -render(self, arguments: dict[str, Any] | None = None) -> PromptResult -``` - -Delegate to child server's render_prompt() without task_meta. - -This is called when the prompt is used within a transformed context -or other contexts where task_meta is not available. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `FastMCPProviderResourceTemplate` - - -Resource template that creates FastMCPProviderResources. - -When `create_resource()` is called, this template creates a -FastMCPProviderResource that will invoke the wrapped server's middleware -when read. - - -**Methods:** - -#### `wrap` - -```python -wrap(cls, server: Any, template: ResourceTemplate) -> FastMCPProviderResourceTemplate -``` - -Wrap a ResourceTemplate to create FastMCPProviderResources. - - -#### `create_resource` - -```python -create_resource(self, uri: str, params: dict[str, Any]) -> Resource -``` - -Create a FastMCPProviderResource for the given URI. - -The `uri` is the external/transformed URI (e.g., with namespace prefix). -We use `_original_uri_template` with `params` to construct the internal -URI that the nested server understands. - - -#### `read` - -```python -read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult -``` - -Read the resource content for background task execution. - -Reads the resource via the wrapped server and returns the ResourceResult. -This method is called by Docket during background task execution. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -No-op: the child's actual template is registered via get_tasks(). - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, params: dict[str, Any], **kwargs: Any) -> Execution -``` - -Schedule this template for background execution via docket. - -The child's FunctionResourceTemplate.fn is registered (via get_tasks), -and it expects splatted **kwargs, so we splat params here. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `FastMCPProvider` - - -Provider that wraps a FastMCP server. - -This provider enables mounting one FastMCP server onto another, exposing -the mounted server's tools, resources, and prompts through the parent -server. - -Components returned by this provider are wrapped in FastMCPProvider* -classes that delegate execution to the wrapped server's middleware chain. -This ensures middleware runs when components are executed. - - -**Methods:** - -#### `get_app_tool` - -```python -get_app_tool(self, app_name: str, tool_name: str) -> Tool | None -``` - -Delegate to nested server's get_app_tool, wrapping for middleware. - - -#### `get_tool_by_hash` - -```python -get_tool_by_hash(self, tool_hash: str, tool_name: str) -> Tool | None -``` - -Delegate to nested server's get_tool_by_hash, wrapping for middleware. - - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Return task-eligible components from the mounted server. - -Returns the child's ACTUAL components (not wrapped) so their actual -functions get registered with Docket. Gets components with child -server's transforms applied, then applies this provider's transforms -for correct registration keys. - - -#### `lifespan` - -```python -lifespan(self) -> AsyncIterator[None] -``` - -Start the mounted server's user lifespan. - -This starts only the wrapped server's user-defined lifespan, NOT its -full _lifespan_manager() (which includes Docket). The parent server's -Docket handles all background tasks. - diff --git a/docs/python-sdk/fastmcp-server-providers-filesystem.mdx b/docs/python-sdk/fastmcp-server-providers-filesystem.mdx deleted file mode 100644 index e0cb8977c..000000000 --- a/docs/python-sdk/fastmcp-server-providers-filesystem.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: filesystem -sidebarTitle: filesystem ---- - -# `fastmcp.server.providers.filesystem` - - -FileSystemProvider for filesystem-based component discovery. - -FileSystemProvider scans a directory for Python files, imports them, and -registers any Tool, Resource, ResourceTemplate, or Prompt objects found. - -Components are created using the standalone decorators from fastmcp.tools, -fastmcp.resources, and fastmcp.prompts: - -Example: - ```python - # In mcp/tools.py - from fastmcp.tools import tool - - @tool - def greet(name: str) -> str: - return f"Hello, {name}!" - - # In main.py - from pathlib import Path - - from fastmcp import FastMCP - from fastmcp.server.providers import FileSystemProvider - - mcp = FastMCP("MyServer", providers=[FileSystemProvider(Path(__file__).parent / "mcp")]) - ``` - - -## Classes - -### `FileSystemProvider` - - -Provider that discovers components from the filesystem. - -Scans a directory for Python files and registers any Tool, Resource, -ResourceTemplate, or Prompt objects found. Components are created using -the standalone decorators: -- @tool from fastmcp.tools -- @resource from fastmcp.resources -- @prompt from fastmcp.prompts - -**Args:** -- `root`: Root directory to scan. Defaults to current directory. -- `reload`: If True, re-scan files on every request (dev mode). -Defaults to False (scan once at init, cache results). - diff --git a/docs/python-sdk/fastmcp-server-providers-filesystem_discovery.mdx b/docs/python-sdk/fastmcp-server-providers-filesystem_discovery.mdx deleted file mode 100644 index 6c7504145..000000000 --- a/docs/python-sdk/fastmcp-server-providers-filesystem_discovery.mdx +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: filesystem_discovery -sidebarTitle: filesystem_discovery ---- - -# `fastmcp.server.providers.filesystem_discovery` - - -File discovery and module import utilities for filesystem-based routing. - -This module provides functions to: -1. Discover Python files in a directory tree -2. Import modules (as packages if __init__.py exists, else directly) -3. Extract decorated components (Tool, Resource, Prompt objects) from imported modules - - -## Functions - -### `discover_files` - -```python -discover_files(root: Path) -> list[Path] -``` - - -Recursively discover all Python files under a directory. - -Excludes __init__.py files (they're for package structure, not components). - -**Args:** -- `root`: Root directory to scan. - -**Returns:** -- List of .py file paths, sorted for deterministic order. - - -### `import_module_from_file` - -```python -import_module_from_file(file_path: Path, provider_root: Path | None = None) -> ModuleType -``` - - -Import a Python file as a module. - -If the file is part of a package (directory has __init__.py), imports -it as a proper package member (relative imports work). Otherwise, -imports directly using spec_from_file_location. - -sys.path is modified only for the duration of the import and restored -immediately after, so no permanent pollution occurs. - -**Args:** -- `file_path`: Path to the Python file. -- `provider_root`: The provider's root directory. Prevents package root -discovery from walking above this boundary into ancestor packages. - -**Returns:** -- The imported module. - -**Raises:** -- `ImportError`: If the module cannot be imported. - - -### `extract_components` - -```python -extract_components(module: ModuleType) -> list[FastMCPComponent] -``` - - -Extract all MCP components from a module. - -Scans all module attributes for instances of Tool, Resource, -ResourceTemplate, or Prompt objects created by standalone decorators, -or functions decorated with @tool/@resource/@prompt that have __fastmcp__ metadata. - -**Args:** -- `module`: The imported module to scan. - -**Returns:** -- List of component objects (Tool, Resource, ResourceTemplate, Prompt). - - -### `discover_and_import` - -```python -discover_and_import(root: Path) -> DiscoveryResult -``` - - -Discover files, import modules, and extract components. - -This is the main entry point for filesystem-based discovery. - -**Args:** -- `root`: Root directory to scan. - -**Returns:** -- DiscoveryResult with components and any failed files. - - -## Classes - -### `DiscoveryResult` - - -Result of filesystem discovery. - diff --git a/docs/python-sdk/fastmcp-server-providers-local_provider-__init__.mdx b/docs/python-sdk/fastmcp-server-providers-local_provider-__init__.mdx deleted file mode 100644 index 5fe082a63..000000000 --- a/docs/python-sdk/fastmcp-server-providers-local_provider-__init__.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.providers.local_provider` - - -LocalProvider for locally-defined MCP components. - -This module provides the `LocalProvider` class that manages tools, resources, -templates, and prompts registered via decorators or direct methods. - diff --git a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-__init__.mdx b/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-__init__.mdx deleted file mode 100644 index d6009a6de..000000000 --- a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-__init__.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.providers.local_provider.decorators` - - -Decorator mixins for LocalProvider. - -This module provides mixin classes that add decorator functionality -to LocalProvider for tools, resources, templates, and prompts. - diff --git a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-prompts.mdx b/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-prompts.mdx deleted file mode 100644 index e7d7d68f9..000000000 --- a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-prompts.mdx +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: prompts -sidebarTitle: prompts ---- - -# `fastmcp.server.providers.local_provider.decorators.prompts` - - -Prompt decorator mixin for LocalProvider. - -This module provides the PromptDecoratorMixin class that adds prompt -registration functionality to LocalProvider. - - -## Classes - -### `PromptDecoratorMixin` - - -Mixin class providing prompt decorator functionality for LocalProvider. - -This mixin contains all methods related to: -- Prompt registration via add_prompt() -- Prompt decorator (@provider.prompt) - - -**Methods:** - -#### `add_prompt` - -```python -add_prompt(self: LocalProvider, prompt: Prompt | Callable[..., Any]) -> Prompt -``` - -Add a prompt to this provider's storage. - -Accepts either a Prompt object or a decorated function with __fastmcp__ metadata. - - -#### `prompt` - -```python -prompt(self: LocalProvider, name_or_fn: F) -> F -``` - -#### `prompt` - -```python -prompt(self: LocalProvider, name_or_fn: str | None = None) -> Callable[[F], F] -``` - -#### `prompt` - -```python -prompt(self: LocalProvider, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt] -``` - -Decorator to register a prompt. - -This decorator supports multiple calling patterns: -- @provider.prompt (without parentheses) -- @provider.prompt() (with empty parentheses) -- @provider.prompt("custom_name") (with name as first argument) -- @provider.prompt(name="custom_name") (with name as keyword argument) -- provider.prompt(function, name="custom_name") (direct function call) - -**Args:** -- `name_or_fn`: Either a function (when used as @prompt), a string name, or None -- `name`: Optional name for the prompt (keyword-only, alternative to name_or_fn) -- `title`: Optional title for the prompt -- `description`: Optional description of what the prompt does -- `icons`: Optional icons for the prompt -- `tags`: Optional set of tags for categorizing the prompt -- `enabled`: Whether the prompt is enabled (default True). If False, adds to blocklist. -- `meta`: Optional meta information about the prompt -- `task`: Optional task configuration for background execution -- `auth`: Optional authorization checks for the prompt - -**Returns:** -- The registered FunctionPrompt or a decorator function. - diff --git a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-resources.mdx b/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-resources.mdx deleted file mode 100644 index 70c67d91c..000000000 --- a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-resources.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: resources -sidebarTitle: resources ---- - -# `fastmcp.server.providers.local_provider.decorators.resources` - - -Resource decorator mixin for LocalProvider. - -This module provides the ResourceDecoratorMixin class that adds resource -and template registration functionality to LocalProvider. - - -## Classes - -### `ResourceDecoratorMixin` - - -Mixin class providing resource decorator functionality for LocalProvider. - -This mixin contains all methods related to: -- Resource registration via add_resource() -- Resource template registration via add_template() -- Resource decorator (@provider.resource) - - -**Methods:** - -#### `add_resource` - -```python -add_resource(self: LocalProvider, resource: Resource | ResourceTemplate | Callable[..., Any]) -> Resource | ResourceTemplate -``` - -Add a resource to this provider's storage. - -Accepts either a Resource/ResourceTemplate object or a decorated function with __fastmcp__ metadata. - - -#### `add_template` - -```python -add_template(self: LocalProvider, template: ResourceTemplate) -> ResourceTemplate -``` - -Add a resource template to this provider's storage. - - -#### `resource` - -```python -resource(self: LocalProvider, uri: str) -> Callable[[F], F] -``` - -Decorator to register a function as a resource. - -If the URI contains parameters (e.g. "resource://{param}") or the function -has parameters, it will be registered as a template resource. - -**Args:** -- `uri`: URI for the resource (e.g. "resource\://my-resource" or "resource\://{param}") -- `name`: Optional name for the resource -- `title`: Optional title for the resource -- `description`: Optional description of the resource -- `icons`: Optional icons for the resource -- `mime_type`: Optional MIME type for the resource -- `tags`: Optional set of tags for categorizing the resource -- `enabled`: Whether the resource is enabled (default True). If False, adds to blocklist. -- `annotations`: Optional annotations about the resource's behavior -- `meta`: Optional meta information about the resource -- `task`: Optional task configuration for background execution -- `auth`: Optional authorization checks for the resource - -**Returns:** -- A decorator function. - diff --git a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-tools.mdx b/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-tools.mdx deleted file mode 100644 index f09ea31f7..000000000 --- a/docs/python-sdk/fastmcp-server-providers-local_provider-decorators-tools.mdx +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: tools -sidebarTitle: tools ---- - -# `fastmcp.server.providers.local_provider.decorators.tools` - - -Tool decorator mixin for LocalProvider. - -This module provides the ToolDecoratorMixin class that adds tool -registration functionality to LocalProvider. - - -## Classes - -### `ToolDecoratorMixin` - - -Mixin class providing tool decorator functionality for LocalProvider. - -This mixin contains all methods related to: -- Tool registration via add_tool() -- Tool decorator (@provider.tool) - - -**Methods:** - -#### `add_tool` - -```python -add_tool(self: LocalProvider, tool: Tool | Callable[..., Any]) -> Tool -``` - -Add a tool to this provider's storage. - -Accepts either a Tool object or a decorated function with __fastmcp__ metadata. - - -#### `tool` - -```python -tool(self: LocalProvider, name_or_fn: F) -> F -``` - -#### `tool` - -```python -tool(self: LocalProvider, name_or_fn: str | None = None) -> Callable[[F], F] -``` - -#### `tool` - -```python -tool(self: LocalProvider, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool] -``` - -Decorator to register a tool. - -This decorator supports multiple calling patterns: -- @provider.tool (without parentheses) -- @provider.tool() (with empty parentheses) -- @provider.tool("custom_name") (with name as first argument) -- @provider.tool(name="custom_name") (with name as keyword argument) -- provider.tool(function, name="custom_name") (direct function call) - -**Args:** -- `name_or_fn`: Either a function (when used as @tool), a string name, or None -- `name`: Optional name for the tool (keyword-only, alternative to name_or_fn) -- `title`: Optional title for the tool -- `description`: Optional description of what the tool does -- `icons`: Optional icons for the tool -- `tags`: Optional set of tags for categorizing the tool -- `output_schema`: Optional JSON schema for the tool's output -- `annotations`: Optional annotations about the tool's behavior -- `exclude_args`: Optional list of argument names to exclude from the tool schema -- `meta`: Optional meta information about the tool -- `enabled`: Whether the tool is enabled (default True). If False, adds to blocklist. -- `task`: Optional task configuration for background execution -- `serializer`: Deprecated. Return ToolResult from your tools for full control over serialization. - -**Returns:** -- The registered FunctionTool or a decorator function. - diff --git a/docs/python-sdk/fastmcp-server-providers-local_provider-local_provider.mdx b/docs/python-sdk/fastmcp-server-providers-local_provider-local_provider.mdx deleted file mode 100644 index f3bc03205..000000000 --- a/docs/python-sdk/fastmcp-server-providers-local_provider-local_provider.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: local_provider -sidebarTitle: local_provider ---- - -# `fastmcp.server.providers.local_provider.local_provider` - - -LocalProvider for locally-defined MCP components. - -This module provides the `LocalProvider` class that manages tools, resources, -templates, and prompts registered via decorators or direct methods. - -LocalProvider can be used standalone and attached to multiple servers: - -```python -from fastmcp.server.providers import LocalProvider - -# Create a reusable provider with tools -provider = LocalProvider() - -@provider.tool -def greet(name: str) -> str: - return f"Hello, {name}!" - -# Attach to any server -from fastmcp import FastMCP -server1 = FastMCP("Server1", providers=[provider]) -server2 = FastMCP("Server2", providers=[provider]) -``` - - -## Classes - -### `LocalProvider` - - -Provider for locally-defined components. - -Supports decorator-based registration (`@provider.tool`, `@provider.resource`, -`@provider.prompt`) and direct object registration methods. - -When used standalone, LocalProvider uses default settings. When attached -to a FastMCP server via the server's decorators, server-level settings -like `_tool_serializer` and `_support_tasks_by_default` are injected. - - -**Methods:** - -#### `remove_tool` - -```python -remove_tool(self, name: str, version: str | None = None) -> None -``` - -Remove tool(s) from this provider's storage. - -**Args:** -- `name`: The tool name. -- `version`: If None, removes ALL versions. If specified, removes only that version. - -**Raises:** -- `KeyError`: If no matching tool is found. - - -#### `remove_resource` - -```python -remove_resource(self, uri: str, version: str | None = None) -> None -``` - -Remove resource(s) from this provider's storage. - -**Args:** -- `uri`: The resource URI. -- `version`: If None, removes ALL versions. If specified, removes only that version. - -**Raises:** -- `KeyError`: If no matching resource is found. - - -#### `remove_template` - -```python -remove_template(self, uri_template: str, version: str | None = None) -> None -``` - -Remove resource template(s) from this provider's storage. - -**Args:** -- `uri_template`: The template URI pattern. -- `version`: If None, removes ALL versions. If specified, removes only that version. - -**Raises:** -- `KeyError`: If no matching template is found. - - -#### `remove_prompt` - -```python -remove_prompt(self, name: str, version: str | None = None) -> None -``` - -Remove prompt(s) from this provider's storage. - -**Args:** -- `name`: The prompt name. -- `version`: If None, removes ALL versions. If specified, removes only that version. - -**Raises:** -- `KeyError`: If no matching prompt is found. - - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Return components eligible for background task execution. - -Returns components that have task_config.mode != 'forbidden'. -This includes both FunctionTool/Resource/Prompt instances created via -decorators and custom Tool/Resource/Prompt subclasses. - diff --git a/docs/python-sdk/fastmcp-server-providers-openapi-__init__.mdx b/docs/python-sdk/fastmcp-server-providers-openapi-__init__.mdx deleted file mode 100644 index bd79a038b..000000000 --- a/docs/python-sdk/fastmcp-server-providers-openapi-__init__.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.providers.openapi` - - -OpenAPI provider for FastMCP. - -This module provides OpenAPI integration for FastMCP through the Provider pattern. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.providers.openapi import OpenAPIProvider - import httpx - - client = httpx.AsyncClient(base_url="https://api.example.com") - provider = OpenAPIProvider(openapi_spec=spec, client=client) - mcp = FastMCP("API Server", providers=[provider]) - ``` - diff --git a/docs/python-sdk/fastmcp-server-providers-openapi-components.mdx b/docs/python-sdk/fastmcp-server-providers-openapi-components.mdx deleted file mode 100644 index f16ecaaeb..000000000 --- a/docs/python-sdk/fastmcp-server-providers-openapi-components.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: components -sidebarTitle: components ---- - -# `fastmcp.server.providers.openapi.components` - - -OpenAPI component classes: Tool, Resource, and ResourceTemplate. - -## Classes - -### `OpenAPITool` - - -Tool implementation for OpenAPI endpoints. - - -**Methods:** - -#### `run` - -```python -run(self, arguments: dict[str, Any]) -> ToolResult -``` - -Execute the HTTP request using RequestDirector. - - -### `OpenAPIResource` - - -Resource implementation for OpenAPI endpoints. - - -**Methods:** - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Fetch the resource data by making an HTTP request. - - -### `OpenAPIResourceTemplate` - - -Resource template implementation for OpenAPI endpoints. - - -**Methods:** - -#### `create_resource` - -```python -create_resource(self, uri: str, params: dict[str, Any], context: Context | None = None) -> Resource -``` - -Create a resource with the given parameters. - diff --git a/docs/python-sdk/fastmcp-server-providers-openapi-provider.mdx b/docs/python-sdk/fastmcp-server-providers-openapi-provider.mdx deleted file mode 100644 index 037c4b7fc..000000000 --- a/docs/python-sdk/fastmcp-server-providers-openapi-provider.mdx +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: provider -sidebarTitle: provider ---- - -# `fastmcp.server.providers.openapi.provider` - - -OpenAPIProvider for creating MCP components from OpenAPI specifications. - -## Classes - -### `OpenAPIProvider` - - -Provider that creates MCP components from an OpenAPI specification. - -Components are created eagerly during initialization by parsing the OpenAPI -spec. Each component makes HTTP calls to the described API endpoints. - - -**Methods:** - -#### `lifespan` - -```python -lifespan(self) -> AsyncIterator[None] -``` - -Manage the lifecycle of the auto-created httpx client. - - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Return empty list - OpenAPI components don't support tasks. - diff --git a/docs/python-sdk/fastmcp-server-providers-openapi-routing.mdx b/docs/python-sdk/fastmcp-server-providers-openapi-routing.mdx deleted file mode 100644 index c35ca5886..000000000 --- a/docs/python-sdk/fastmcp-server-providers-openapi-routing.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: routing -sidebarTitle: routing ---- - -# `fastmcp.server.providers.openapi.routing` - - -Route mapping logic for OpenAPI operations. - -## Classes - -### `MCPType` - - -Type of FastMCP component to create from a route. - - -### `RouteMap` - - -Mapping configuration for HTTP routes to FastMCP component types. - diff --git a/docs/python-sdk/fastmcp-server-providers-prefab_synthesis.mdx b/docs/python-sdk/fastmcp-server-providers-prefab_synthesis.mdx deleted file mode 100644 index c06fc8b7a..000000000 --- a/docs/python-sdk/fastmcp-server-providers-prefab_synthesis.mdx +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: prefab_synthesis -sidebarTitle: prefab_synthesis ---- - -# `fastmcp.server.providers.prefab_synthesis` - - -On-demand Prefab renderer resource synthesis. - -Tools marked as Prefab (via ``app=True``, ``PrefabAppConfig``, etc.) carry -a placeholder ``meta.ui.resourceUri`` and optionally a hash in -``meta.fastmcp._tool_hash``. This module synthesizes per-tool renderer -resources on demand at ``list_resources`` and ``read_resource`` time -without storing or materializing anything. - -Each tool's resource URI is ``ui://prefab/tool//renderer.html`` -where the hash comes from the tool's own meta (set at registration from -the app name + tool name). CSP on the resource is the tool's -``meta.ui.csp`` merged with the renderer defaults across all four -``*_domains`` fields. - - -## Functions - -### `synthesize_prefab_resources` - -```python -synthesize_prefab_resources(server: FastMCP) -> list[Resource] -``` - - -Return fresh synthetic Prefab resources for all prefab tools. Pure. - - -### `synthesize_prefab_resource_by_uri` - -```python -synthesize_prefab_resource_by_uri(server: FastMCP, uri: str) -> Resource | None -``` - - -Intercept a Prefab renderer URI and synthesize on demand. - - -### `rewrite_tool_meta_for_wire` - -```python -rewrite_tool_meta_for_wire(tool: Tool) -> Tool -``` - - -Return a model_copy with the per-tool URI and CSP stripped. - -Reads the hash from the tool's own meta. If no hash is found, -returns the tool unchanged. Produces a fresh copy — the original -Tool object is untouched. - diff --git a/docs/python-sdk/fastmcp-server-providers-proxy.mdx b/docs/python-sdk/fastmcp-server-providers-proxy.mdx deleted file mode 100644 index c9f0a6b2f..000000000 --- a/docs/python-sdk/fastmcp-server-providers-proxy.mdx +++ /dev/null @@ -1,327 +0,0 @@ ---- -title: proxy -sidebarTitle: proxy ---- - -# `fastmcp.server.providers.proxy` - - -ProxyProvider for proxying to remote MCP servers. - -This module provides the `ProxyProvider` class that proxies components from -a remote MCP server via a client factory. It also provides proxy component -classes that forward execution to remote servers. - - -## Functions - -### `default_proxy_roots_handler` - -```python -default_proxy_roots_handler(context: RequestContext[ClientSession, LifespanContextT]) -> RootsList -``` - - -Forward list roots request from remote server to proxy's connected clients. - - -### `default_proxy_sampling_handler` - -```python -default_proxy_sampling_handler(messages: list[mcp.types.SamplingMessage], params: mcp.types.CreateMessageRequestParams, context: RequestContext[ClientSession, LifespanContextT]) -> mcp.types.CreateMessageResult -``` - - -Forward sampling request from remote server to proxy's connected clients. - - -### `default_proxy_elicitation_handler` - -```python -default_proxy_elicitation_handler(message: str, response_type: type, params: mcp.types.ElicitRequestParams, context: RequestContext[ClientSession, LifespanContextT]) -> ElicitResult -``` - - -Forward elicitation request from remote server to proxy's connected clients. - - -### `default_proxy_log_handler` - -```python -default_proxy_log_handler(message: LogMessage) -> None -``` - - -Forward log notification from remote server to proxy's connected clients. - - -### `default_proxy_progress_handler` - -```python -default_proxy_progress_handler(progress: float, total: float | None, message: str | None) -> None -``` - - -Forward progress notification from remote server to proxy's connected clients. - - -## Classes - -### `ProxyTool` - - -A Tool that represents and executes a tool on a remote server. - - -**Methods:** - -#### `model_copy` - -```python -model_copy(self, **kwargs: Any) -> ProxyTool -``` - -Override to preserve _backend_name when name changes. - - -#### `from_mcp_tool` - -```python -from_mcp_tool(cls, client_factory: ClientFactoryT, mcp_tool: mcp.types.Tool) -> ProxyTool -``` - -Factory method to create a ProxyTool from a raw MCP tool schema. - - -#### `run` - -```python -run(self, arguments: dict[str, Any], context: Context | None = None) -> ToolResult -``` - -Executes the tool by making a call through the client. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `ProxyResource` - - -A Resource that represents and reads a resource from a remote server. - - -**Methods:** - -#### `model_copy` - -```python -model_copy(self, **kwargs: Any) -> ProxyResource -``` - -Override to preserve _backend_uri when uri changes. - - -#### `from_mcp_resource` - -```python -from_mcp_resource(cls, client_factory: ClientFactoryT, mcp_resource: mcp.types.Resource) -> ProxyResource -``` - -Factory method to create a ProxyResource from a raw MCP resource schema. - - -#### `read` - -```python -read(self) -> ResourceResult -``` - -Read the resource content from the remote server. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `ProxyTemplate` - - -A ResourceTemplate that represents and creates resources from a remote server template. - - -**Methods:** - -#### `model_copy` - -```python -model_copy(self, **kwargs: Any) -> ProxyTemplate -``` - -Override to preserve _backend_uri_template when uri_template changes. - - -#### `from_mcp_template` - -```python -from_mcp_template(cls, client_factory: ClientFactoryT, mcp_template: mcp.types.ResourceTemplate) -> ProxyTemplate -``` - -Factory method to create a ProxyTemplate from a raw MCP template schema. - - -#### `create_resource` - -```python -create_resource(self, uri: str, params: dict[str, Any], context: Context | None = None) -> ProxyResource -``` - -Create a resource from the template by calling the remote server. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `ProxyPrompt` - - -A Prompt that represents and renders a prompt from a remote server. - - -**Methods:** - -#### `model_copy` - -```python -model_copy(self, **kwargs: Any) -> ProxyPrompt -``` - -Override to preserve _backend_name when name changes. - - -#### `from_mcp_prompt` - -```python -from_mcp_prompt(cls, client_factory: ClientFactoryT, mcp_prompt: mcp.types.Prompt) -> ProxyPrompt -``` - -Factory method to create a ProxyPrompt from a raw MCP prompt schema. - - -#### `render` - -```python -render(self, arguments: dict[str, Any]) -> PromptResult -``` - -Render the prompt by making a call through the client. - - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` - -### `ProxyProvider` - - -Provider that proxies to a remote MCP server via a client factory. - -This provider fetches components from a remote server and returns Proxy* -component instances that forward execution to the remote server. - -All components returned by this provider have task_config.mode="forbidden" -because tasks cannot be executed through a proxy. - -Component lists (tools, resources, templates, prompts) are cached so that -individual lookups (e.g. during ``call_tool``) can resolve from the cache -instead of opening a new backend connection. The cache stores the -backend's raw component metadata and is shared across all sessions; -per-session visibility and auth filtering are applied after cache lookup -by the server layer. The cache is refreshed whenever a ``list_*`` call -is made, and entries expire after ``cache_ttl`` seconds (default 300). -Set ``cache_ttl=0`` to disable caching. Disabling is recommended for -backends whose component lists change dynamically. - - -**Methods:** - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Return empty list since proxy components don't support tasks. - -Override the base implementation to avoid calling list_tools() during -server lifespan initialization, which would open the client before any -context is set. All Proxy* components have task_config.mode="forbidden". - - -### `FastMCPProxy` - - -A FastMCP server that acts as a proxy to a remote MCP-compliant server. - -This is a convenience wrapper that creates a FastMCP server with a -ProxyProvider. For more control, use FastMCP with add_provider(ProxyProvider(...)). - - -### `ProxyClient` - - -A proxy client that forwards advanced interactions between a remote MCP server and the proxy's connected clients. - -Supports forwarding roots, sampling, elicitation, logging, and progress. - - -### `StatefulProxyClient` - - -A proxy client that provides a stateful client factory for the proxy server. - -The stateful proxy client bound its copy to the server session. -And it will be disconnected when the session is exited. - -This is useful to proxy a stateful mcp server such as the Playwright MCP server. -Note that it is essential to ensure that the proxy server itself is also stateful. - -Because session reuse means the receive-loop task inherits a stale -``request_ctx`` ContextVar snapshot, the default proxy handlers are -replaced with versions that restore the ContextVar before forwarding. -``ProxyTool.run`` stashes the current ``RequestContext`` in -``_proxy_rc_ref`` before each backend call, and the handlers consult -it to detect (and correct) staleness. - - -**Methods:** - -#### `clear` - -```python -clear(self) -``` - -Clear all cached clients and force disconnect them. - - -#### `new_stateful` - -```python -new_stateful(self) -> Client[ClientTransportT] -``` - -Create a new stateful proxy client instance with the same configuration. - -Use this method as the client factory for stateful proxy server. - diff --git a/docs/python-sdk/fastmcp-server-providers-skills-__init__.mdx b/docs/python-sdk/fastmcp-server-providers-skills-__init__.mdx deleted file mode 100644 index c3f296111..000000000 --- a/docs/python-sdk/fastmcp-server-providers-skills-__init__.mdx +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.providers.skills` - - -Skills providers for exposing agent skills as MCP resources. - -This module provides a two-layer architecture for skill discovery: - -- **SkillProvider**: Handles a single skill folder, exposing its files as resources. -- **SkillsDirectoryProvider**: Scans a directory, creates a SkillProvider per folder. -- **Vendor providers**: Platform-specific providers for Claude, Cursor, VS Code, Codex, - Gemini, Goose, Copilot, and OpenCode. - -Example: - ```python - from pathlib import Path - from fastmcp import FastMCP - from fastmcp.server.providers.skills import ClaudeSkillsProvider, SkillProvider - - mcp = FastMCP("Skills Server") - - # Load a single skill - mcp.add_provider(SkillProvider(Path.home() / ".claude/skills/pdf-processing")) - - # Or load all skills in a directory - mcp.add_provider(ClaudeSkillsProvider()) # Uses ~/.claude/skills/ - ``` - diff --git a/docs/python-sdk/fastmcp-server-providers-skills-claude_provider.mdx b/docs/python-sdk/fastmcp-server-providers-skills-claude_provider.mdx deleted file mode 100644 index 30ed2c7c7..000000000 --- a/docs/python-sdk/fastmcp-server-providers-skills-claude_provider.mdx +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: claude_provider -sidebarTitle: claude_provider ---- - -# `fastmcp.server.providers.skills.claude_provider` - - -Claude-specific skills provider for Claude Code skills. - -## Classes - -### `ClaudeSkillsProvider` - - -Provider for Claude Code skills from ~/.claude/skills/. - -A convenience subclass that sets the default root to Claude's skills location. - -**Args:** -- `reload`: If True, re-scan on every request. Defaults to False. -- `supporting_files`: How supporting files are exposed\: -- "template"\: Accessed via ResourceTemplate, hidden from list_resources(). -- "resources"\: Each file exposed as individual Resource in list_resources(). - diff --git a/docs/python-sdk/fastmcp-server-providers-skills-directory_provider.mdx b/docs/python-sdk/fastmcp-server-providers-skills-directory_provider.mdx deleted file mode 100644 index bf68a00e3..000000000 --- a/docs/python-sdk/fastmcp-server-providers-skills-directory_provider.mdx +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: directory_provider -sidebarTitle: directory_provider ---- - -# `fastmcp.server.providers.skills.directory_provider` - - -Directory scanning provider for discovering multiple skills. - -## Classes - -### `SkillsDirectoryProvider` - - -Provider that scans directories and creates a SkillProvider per skill folder. - -This extends AggregateProvider to combine multiple SkillProviders into one. -Each subdirectory containing a main file (default: SKILL.md) becomes a skill. -Can scan multiple root directories - if a skill name appears in multiple roots, -the first one found wins. - -**Args:** -- `roots`: Root directory(ies) containing skill folders. Can be a single path -or a sequence of paths. -- `reload`: If True, re-discover skills on each request. Defaults to False. -- `main_file_name`: Name of the main skill file. Defaults to "SKILL.md". -- `supporting_files`: How supporting files are exposed in child SkillProviders\: -- "template"\: Accessed via ResourceTemplate, hidden from list_resources(). -- "resources"\: Each file exposed as individual Resource in list_resources(). - diff --git a/docs/python-sdk/fastmcp-server-providers-skills-skill_provider.mdx b/docs/python-sdk/fastmcp-server-providers-skills-skill_provider.mdx deleted file mode 100644 index c1ab56d9d..000000000 --- a/docs/python-sdk/fastmcp-server-providers-skills-skill_provider.mdx +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: skill_provider -sidebarTitle: skill_provider ---- - -# `fastmcp.server.providers.skills.skill_provider` - - -Basic skill provider for handling a single skill folder. - -## Classes - -### `SkillResource` - - -A resource representing a skill's main file or manifest. - - -**Methods:** - -#### `get_meta` - -```python -get_meta(self) -> dict[str, Any] -``` - -#### `read` - -```python -read(self) -> str | bytes | ResourceResult -``` - -Read the resource content. - - -### `SkillFileTemplate` - - -A template for accessing files within a skill. - - -**Methods:** - -#### `read` - -```python -read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult -``` - -Read a file from the skill directory. - - -#### `create_resource` - -```python -create_resource(self, uri: str, params: dict[str, Any]) -> Resource -``` - -Create a resource for the given URI and parameters. - -Note: This is not typically used since _read() handles file reading directly. -Provided for compatibility with the ResourceTemplate interface. - - -### `SkillFileResource` - - -A resource representing a specific file within a skill. - - -**Methods:** - -#### `get_meta` - -```python -get_meta(self) -> dict[str, Any] -``` - -#### `read` - -```python -read(self) -> str | bytes | ResourceResult -``` - -Read the file content. - - -### `SkillProvider` - - -Provider that exposes a single skill folder as MCP resources. - -Each skill folder must contain a main file (default: SKILL.md) and may -contain additional supporting files. - -Exposes: -- A Resource for the main file (skill://{name}/SKILL.md) -- A Resource for the synthetic manifest (skill://{name}/_manifest) -- Supporting files via ResourceTemplate or Resources (configurable) - -**Args:** -- `skill_path`: Path to the skill directory. -- `main_file_name`: Name of the main skill file. Defaults to "SKILL.md". -- `supporting_files`: How supporting files (everything except main file and -manifest) are exposed to clients\: -- "template"\: Accessed via ResourceTemplate, hidden from list_resources(). - Clients discover files by reading the manifest first. -- "resources"\: Each file exposed as individual Resource in list_resources(). - Full enumeration upfront. - - -**Methods:** - -#### `skill_info` - -```python -skill_info(self) -> SkillInfo -``` - -Get the loaded skill info. - diff --git a/docs/python-sdk/fastmcp-server-providers-skills-vendor_providers.mdx b/docs/python-sdk/fastmcp-server-providers-skills-vendor_providers.mdx deleted file mode 100644 index a5a724953..000000000 --- a/docs/python-sdk/fastmcp-server-providers-skills-vendor_providers.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: vendor_providers -sidebarTitle: vendor_providers ---- - -# `fastmcp.server.providers.skills.vendor_providers` - - -Vendor-specific skills providers for various AI coding platforms. - -## Classes - -### `CursorSkillsProvider` - - -Cursor skills from ~/.cursor/skills/. - - -### `VSCodeSkillsProvider` - - -VS Code skills from ~/.copilot/skills/. - - -### `CodexSkillsProvider` - - -Codex skills from /etc/codex/skills/ and ~/.codex/skills/. - -Scans both system-level and user-level directories. System skills take -precedence if duplicates exist. - - -### `GeminiSkillsProvider` - - -Gemini skills from ~/.gemini/skills/. - - -### `GooseSkillsProvider` - - -Goose skills from ~/.config/agents/skills/. - - -### `CopilotSkillsProvider` - - -GitHub Copilot skills from ~/.copilot/skills/. - - -### `OpenCodeSkillsProvider` - - -OpenCode skills from ~/.config/opencode/skills/. - diff --git a/docs/python-sdk/fastmcp-server-providers-wrapped_provider.mdx b/docs/python-sdk/fastmcp-server-providers-wrapped_provider.mdx deleted file mode 100644 index 22fc90b40..000000000 --- a/docs/python-sdk/fastmcp-server-providers-wrapped_provider.mdx +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: wrapped_provider -sidebarTitle: wrapped_provider ---- - -# `fastmcp.server.providers.wrapped_provider` - - -WrappedProvider for immutable transform composition. - -This module provides `_WrappedProvider`, an internal class that wraps a provider -with an additional transform. Created by `Provider.wrap_transform()`. - diff --git a/docs/python-sdk/fastmcp-server-proxy.mdx b/docs/python-sdk/fastmcp-server-proxy.mdx deleted file mode 100644 index a9200635c..000000000 --- a/docs/python-sdk/fastmcp-server-proxy.mdx +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: proxy -sidebarTitle: proxy ---- - -# `fastmcp.server.proxy` - - -Backwards compatibility - import from fastmcp.server.providers.proxy instead. - -This module re-exports all proxy-related classes from their new location -at fastmcp.server.providers.proxy. Direct imports from this module are -deprecated and will be removed in a future version. - diff --git a/docs/python-sdk/fastmcp-server-sampling-__init__.mdx b/docs/python-sdk/fastmcp-server-sampling-__init__.mdx deleted file mode 100644 index 0b0533971..000000000 --- a/docs/python-sdk/fastmcp-server-sampling-__init__.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.sampling` - - -Sampling module for FastMCP servers. diff --git a/docs/python-sdk/fastmcp-server-sampling-run.mdx b/docs/python-sdk/fastmcp-server-sampling-run.mdx deleted file mode 100644 index 09d87f4ae..000000000 --- a/docs/python-sdk/fastmcp-server-sampling-run.mdx +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: run -sidebarTitle: run ---- - -# `fastmcp.server.sampling.run` - - -Sampling types and helper functions for FastMCP servers. - -## Functions - -### `determine_handler_mode` - -```python -determine_handler_mode(context: Context, needs_tools: bool) -> bool -``` - - -Determine whether to use fallback handler or client for sampling. - -**Args:** -- `context`: The MCP context. -- `needs_tools`: Whether the sampling request requires tool support. - -**Returns:** -- True if fallback handler should be used, False to use client. - -**Raises:** -- `ValueError`: If client lacks required capability and no fallback configured. - - -### `call_sampling_handler` - -```python -call_sampling_handler(context: Context, messages: list[SamplingMessage]) -> CreateMessageResult | CreateMessageResultWithTools -``` - - -Make LLM call using the fallback handler. - -Note: This function expects the caller (sample_step) to have validated that -sampling_handler is set via determine_handler_mode(). The checks below are -safeguards against internal misuse. - - -### `execute_tools` - -```python -execute_tools(tool_calls: list[ToolUseContent], tool_map: dict[str, SamplingTool], mask_error_details: bool = False, tool_concurrency: int | None = None) -> list[ToolResultContent] -``` - - -Execute tool calls and return results. - -**Args:** -- `tool_calls`: List of tool use requests from the LLM. -- `tool_map`: Mapping from tool name to SamplingTool. -- `mask_error_details`: If True, mask detailed error messages from tool execution. -When masked, only generic error messages are returned to the LLM. -Tools can explicitly raise ToolError to bypass masking when they want -to provide specific error messages to the LLM. -- `tool_concurrency`: Controls parallel execution of tools\: -- None (default)\: Sequential execution (one at a time) -- 0\: Unlimited parallel execution -- N > 0\: Execute at most N tools concurrently -If any tool has sequential=True, all tools execute sequentially -regardless of this setting. - -**Returns:** -- List of tool result content blocks in the same order as tool_calls. - - -### `prepare_messages` - -```python -prepare_messages(messages: str | Sequence[str | SamplingMessage]) -> list[SamplingMessage] -``` - - -Convert various message formats to a list of SamplingMessage objects. - - -### `prepare_tools` - -```python -prepare_tools(tools: Sequence[SamplingTool | FunctionTool | TransformedTool | Callable[..., Any]] | None) -> list[SamplingTool] | None -``` - - -Convert tools to SamplingTool objects. - -Accepts SamplingTool instances, FunctionTool instances, TransformedTool instances, -or plain callable functions. FunctionTool and TransformedTool are converted using -from_callable_tool(), while plain functions use from_function(). - -**Args:** -- `tools`: Sequence of tools to prepare. Can be SamplingTool, FunctionTool, -TransformedTool, or plain callable functions. - -**Returns:** -- List of SamplingTool instances, or None if tools is None. - - -### `extract_tool_calls` - -```python -extract_tool_calls(response: CreateMessageResult | CreateMessageResultWithTools) -> list[ToolUseContent] -``` - - -Extract tool calls from a response. - - -### `create_final_response_tool` - -```python -create_final_response_tool(result_type: type) -> SamplingTool -``` - - -Create a synthetic 'final_response' tool for structured output. - -This tool is used to capture structured responses from the LLM. -The tool's schema is derived from the result_type. - - -### `sample_step_impl` - -```python -sample_step_impl(context: Context, messages: str | Sequence[str | SamplingMessage]) -> SampleStep -``` - - -Implementation of Context.sample_step(). - -Make a single LLM sampling call. This is a stateless function that makes -exactly one LLM call and optionally executes any requested tools. - - -### `sample_impl` - -```python -sample_impl(context: Context, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] -``` - - -Implementation of Context.sample(). - -Send a sampling request to the client and await the response. This method -runs to completion automatically, executing a tool loop until the LLM -provides a final text response. - - -## Classes - -### `SamplingResult` - - -Result of a sampling operation. - -**Attributes:** -- `text`: The text representation of the result (raw text or JSON for structured). -- `result`: The typed result (str for text, parsed object for structured output). -- `history`: All messages exchanged during sampling. - - -### `SampleStep` - - -Result of a single sampling call. - -Represents what the LLM returned in this step plus the message history. - - -**Methods:** - -#### `is_tool_use` - -```python -is_tool_use(self) -> bool -``` - -True if the LLM is requesting tool execution. - - -#### `text` - -```python -text(self) -> str | None -``` - -Extract text from the response, if available. - - -#### `tool_calls` - -```python -tool_calls(self) -> list[ToolUseContent] -``` - -Get the list of tool calls from the response. - diff --git a/docs/python-sdk/fastmcp-server-sampling-sampling_tool.mdx b/docs/python-sdk/fastmcp-server-sampling-sampling_tool.mdx deleted file mode 100644 index 2a3590003..000000000 --- a/docs/python-sdk/fastmcp-server-sampling-sampling_tool.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: sampling_tool -sidebarTitle: sampling_tool ---- - -# `fastmcp.server.sampling.sampling_tool` - - -SamplingTool for use during LLM sampling requests. - -## Classes - -### `SamplingTool` - - -A tool that can be used during LLM sampling. - -SamplingTools bundle a tool's schema (name, description, parameters) with -an executor function, enabling servers to execute agentic workflows where -the LLM can request tool calls during sampling. - -In most cases, pass functions directly to ctx.sample(): - - def search(query: str) -> str: - '''Search the web.''' - return web_search(query) - - result = await context.sample( - messages="Find info about Python", - tools=[search], # Plain functions work directly - ) - -Create a SamplingTool explicitly when you need custom name/description: - - tool = SamplingTool.from_function(search, name="web_search") - - -**Methods:** - -#### `run` - -```python -run(self, arguments: dict[str, Any] | None = None) -> Any -``` - -Execute the tool with the given arguments. - -**Args:** -- `arguments`: Dictionary of arguments to pass to the tool function. - -**Returns:** -- The result of executing the tool function. - - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any]) -> SamplingTool -``` - -Create a SamplingTool from a function. - -The function's signature is analyzed to generate a JSON schema for -the tool's parameters. Type hints are used to determine parameter types. - -**Args:** -- `fn`: The function to create a tool from. -- `name`: Optional name override. Defaults to the function's name. -- `description`: Optional description override. Defaults to the function's docstring. -- `sequential`: If True, this tool requires sequential execution and prevents -parallel execution of all tools in the batch. Set to True for tools -with shared state, file writes, or other operations that cannot run -concurrently. Defaults to False. - -**Returns:** -- A SamplingTool wrapping the function. - -**Raises:** -- `ValueError`: If the function is a lambda without a name override. - - -#### `from_callable_tool` - -```python -from_callable_tool(cls, tool: FunctionTool | TransformedTool) -> SamplingTool -``` - -Create a SamplingTool from a FunctionTool or TransformedTool. - -Reuses existing server tools in sampling contexts. For TransformedTool, -the tool's .run() method is used to ensure proper argument transformation, -and the ToolResult is automatically unwrapped. - -**Args:** -- `tool`: A FunctionTool or TransformedTool to convert. -- `name`: Optional name override. Defaults to tool.name. -- `description`: Optional description override. Defaults to tool.description. - -**Raises:** -- `TypeError`: If the tool is not a FunctionTool or TransformedTool. - diff --git a/docs/python-sdk/fastmcp-server-server.mdx b/docs/python-sdk/fastmcp-server-server.mdx deleted file mode 100644 index f9ef01991..000000000 --- a/docs/python-sdk/fastmcp-server-server.mdx +++ /dev/null @@ -1,922 +0,0 @@ ---- -title: server -sidebarTitle: server ---- - -# `fastmcp.server.server` - - -FastMCP - A more ergonomic interface for MCP servers. - -## Functions - -### `default_lifespan` - -```python -default_lifespan(server: FastMCP[LifespanResultT]) -> AsyncIterator[Any] -``` - - -Default lifespan context manager that does nothing. - -**Args:** -- `server`: The server instance this lifespan is managing - -**Returns:** -- An empty dictionary as the lifespan result. - - -### `create_proxy` - -```python -create_proxy(target: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy -``` - - -Create a FastMCP proxy server for the given target. - -This is the recommended way to create a proxy server. For lower-level control, -use `FastMCPProxy` or `ProxyProvider` directly from `fastmcp.server.providers.proxy`. - -**Args:** -- `target`: The backend to proxy to. Can be\: -- A Client instance (connected or disconnected) -- A ClientTransport -- A FastMCP server instance -- A URL string or AnyUrl -- A Path to a server script -- An MCPConfig or dict -- `**settings`: Additional settings passed to FastMCPProxy (name, etc.) - -**Returns:** -- A FastMCPProxy server that proxies to the target. - - -## Classes - -### `StateValue` - - -Wrapper for stored context state values. - - -### `FastMCP` - -**Methods:** - -#### `name` - -```python -name(self) -> str -``` - -#### `instructions` - -```python -instructions(self) -> str | None -``` - -#### `instructions` - -```python -instructions(self, value: str | None) -> None -``` - -#### `version` - -```python -version(self) -> str | None -``` - -#### `website_url` - -```python -website_url(self) -> str | None -``` - -#### `icons` - -```python -icons(self) -> list[mcp.types.Icon] -``` - -#### `local_provider` - -```python -local_provider(self) -> LocalProvider -``` - -The server's local provider, which stores directly-registered components. - -Use this to remove components: - - mcp.local_provider.remove_tool("my_tool") - mcp.local_provider.remove_resource("data://info") - mcp.local_provider.remove_prompt("my_prompt") - - -#### `add_middleware` - -```python -add_middleware(self, middleware: Middleware) -> None -``` - -#### `add_provider` - -```python -add_provider(self, provider: Provider) -> None -``` - -Add a provider for dynamic tools, resources, and prompts. - -Providers are queried in registration order. The first provider to return -a non-None result wins. Static components (registered via decorators) -always take precedence over providers. - -**Args:** -- `provider`: A Provider instance that will provide components dynamically. -- `namespace`: Optional namespace prefix. When set\: -- Tools become "namespace_toolname" -- Resources become "protocol\://namespace/path" -- Prompts become "namespace_promptname" - - -#### `get_tasks` - -```python -get_tasks(self) -> Sequence[FastMCPComponent] -``` - -Get task-eligible components with all transforms applied. - -Overrides AggregateProvider.get_tasks() to apply server-level transforms -after aggregation. AggregateProvider handles provider-level namespacing. - - -#### `add_transform` - -```python -add_transform(self, transform: Transform) -> None -``` - -Add a server-level transform. - -Server-level transforms are applied after all providers are aggregated. -They transform tools, resources, and prompts from ALL providers. - -**Args:** -- `transform`: The transform to add. - - -#### `add_tool_transformation` - -```python -add_tool_transformation(self, tool_name: str, transformation: ToolTransformConfig) -> None -``` - -Add a tool transformation. - -.. deprecated:: - Use ``add_transform(ToolTransform({...}))`` instead. - - -#### `remove_tool_transformation` - -```python -remove_tool_transformation(self, _tool_name: str) -> None -``` - -Remove a tool transformation. - -.. deprecated:: - Tool transformations are now immutable. Use enable/disable controls instead. - - -#### `list_tools` - -```python -list_tools(self) -> Sequence[Tool] -``` - -List all enabled tools from providers. - -Overrides Provider.list_tools() to add visibility filtering, auth filtering, -and middleware execution. Returns all versions (no deduplication). -Protocol handlers deduplicate for MCP wire format. - - -#### `get_tool` - -```python -get_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None -``` - -Get a tool by name, filtering disabled tools. - -Overrides Provider.get_tool() to add visibility filtering after all -transforms (including session-level) have been applied. This ensures -session transforms can override provider-level disables. - -When the highest version is disabled and no explicit version was -requested, falls back to the next-highest enabled version. - -**Args:** -- `name`: The tool name. -- `version`: Version filter (None returns highest version). - -**Returns:** -- The tool if found and enabled, None otherwise. - - -#### `list_resources` - -```python -list_resources(self) -> Sequence[Resource] -``` - -List all enabled resources from providers. - -Overrides Provider.list_resources() to add visibility filtering, auth filtering, -and middleware execution. Returns all versions (no deduplication). -Protocol handlers deduplicate for MCP wire format. - - -#### `get_resource` - -```python -get_resource(self, uri: str, version: VersionSpec | None = None) -> Resource | None -``` - -Get a resource by URI, filtering disabled resources. - -Overrides Provider.get_resource() to add visibility filtering after all -transforms (including session-level) have been applied. - -When the highest version is disabled and no explicit version was -requested, falls back to the next-highest enabled version. - -**Args:** -- `uri`: The resource URI. -- `version`: Version filter (None returns highest version). - -**Returns:** -- The resource if found and enabled, None otherwise. - - -#### `list_resource_templates` - -```python -list_resource_templates(self) -> Sequence[ResourceTemplate] -``` - -List all enabled resource templates from providers. - -Overrides Provider.list_resource_templates() to add visibility filtering, -auth filtering, and middleware execution. Returns all versions (no deduplication). -Protocol handlers deduplicate for MCP wire format. - - -#### `get_resource_template` - -```python -get_resource_template(self, uri: str, version: VersionSpec | None = None) -> ResourceTemplate | None -``` - -Get a resource template by URI, filtering disabled templates. - -Overrides Provider.get_resource_template() to add visibility filtering after -all transforms (including session-level) have been applied. - -When the highest version is disabled and no explicit version was -requested, falls back to the next-highest enabled version. - -**Args:** -- `uri`: The template URI. -- `version`: Version filter (None returns highest version). - -**Returns:** -- The template if found and enabled, None otherwise. - - -#### `list_prompts` - -```python -list_prompts(self) -> Sequence[Prompt] -``` - -List all enabled prompts from providers. - -Overrides Provider.list_prompts() to add visibility filtering, auth filtering, -and middleware execution. Returns all versions (no deduplication). -Protocol handlers deduplicate for MCP wire format. - - -#### `get_prompt` - -```python -get_prompt(self, name: str, version: VersionSpec | None = None) -> Prompt | None -``` - -Get a prompt by name, filtering disabled prompts. - -Overrides Provider.get_prompt() to add visibility filtering after all -transforms (including session-level) have been applied. - -When the highest version is disabled and no explicit version was -requested, falls back to the next-highest enabled version. - -**Args:** -- `name`: The prompt name. -- `version`: Version filter (None returns highest version). - -**Returns:** -- The prompt if found and enabled, None otherwise. - - -#### `call_tool` - -```python -call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult -``` - -#### `call_tool` - -```python -call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.CreateTaskResult -``` - -#### `call_tool` - -```python -call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult | mcp.types.CreateTaskResult -``` - -Call a tool by name. - -This is the public API for executing tools. By default, middleware is applied. - -**Args:** -- `name`: The tool name -- `arguments`: Tool arguments (optional) -- `version`: Specific version to call. If None, calls highest version. -- `run_middleware`: If True (default), apply the middleware chain. -Set to False when called from middleware to avoid re-applying. -- `task_meta`: If provided, execute as a background task and return -CreateTaskResult. If None (default), execute synchronously and -return ToolResult. - -**Returns:** -- ToolResult when task_meta is None. -- CreateTaskResult when task_meta is provided. - -**Raises:** -- `NotFoundError`: If tool not found or disabled -- `ToolError`: If tool execution fails -- `ValidationError`: If arguments fail validation - - -#### `read_resource` - -```python -read_resource(self, uri: str) -> ResourceResult -``` - -#### `read_resource` - -```python -read_resource(self, uri: str) -> mcp.types.CreateTaskResult -``` - -#### `read_resource` - -```python -read_resource(self, uri: str) -> ResourceResult | mcp.types.CreateTaskResult -``` - -Read a resource by URI. - -This is the public API for reading resources. By default, middleware is applied. -Checks concrete resources first, then templates. - -**Args:** -- `uri`: The resource URI -- `version`: Specific version to read. If None, reads highest version. -- `run_middleware`: If True (default), apply the middleware chain. -Set to False when called from middleware to avoid re-applying. -- `task_meta`: If provided, execute as a background task and return -CreateTaskResult. If None (default), execute synchronously and -return ResourceResult. - -**Returns:** -- ResourceResult when task_meta is None. -- CreateTaskResult when task_meta is provided. - -**Raises:** -- `NotFoundError`: If resource not found or disabled -- `ResourceError`: If resource read fails - - -#### `render_prompt` - -```python -render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> PromptResult -``` - -#### `render_prompt` - -```python -render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.CreateTaskResult -``` - -#### `render_prompt` - -```python -render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> PromptResult | mcp.types.CreateTaskResult -``` - -Render a prompt by name. - -This is the public API for rendering prompts. By default, middleware is applied. -Use get_prompt() to retrieve the prompt definition without rendering. - -**Args:** -- `name`: The prompt name -- `arguments`: Prompt arguments (optional) -- `version`: Specific version to render. If None, renders highest version. -- `run_middleware`: If True (default), apply the middleware chain. -Set to False when called from middleware to avoid re-applying. -- `task_meta`: If provided, execute as a background task and return -CreateTaskResult. If None (default), execute synchronously and -return PromptResult. - -**Returns:** -- PromptResult when task_meta is None. -- CreateTaskResult when task_meta is provided. - -**Raises:** -- `NotFoundError`: If prompt not found or disabled -- `PromptError`: If prompt rendering fails - - -#### `add_tool` - -```python -add_tool(self, tool: Tool | Callable[..., Any]) -> Tool -``` - -Add a tool to the server. - -The tool function can optionally request a Context object by adding a parameter -with the Context type annotation. See the @tool decorator for examples. - -**Args:** -- `tool`: The Tool instance or @tool-decorated function to register - -**Returns:** -- The tool instance that was added to the server. - - -#### `remove_tool` - -```python -remove_tool(self, name: str, version: str | None = None) -> None -``` - -Remove tool(s) from the server. - -.. deprecated:: - Use ``mcp.local_provider.remove_tool(name)`` instead. - -**Args:** -- `name`: The name of the tool to remove. -- `version`: If None, removes ALL versions. If specified, removes only that version. - -**Raises:** -- `NotFoundError`: If no matching tool is found. - - -#### `tool` - -```python -tool(self, name_or_fn: F) -> F -``` - -#### `tool` - -```python -tool(self, name_or_fn: str | None = None) -> Callable[[F], F] -``` - -#### `tool` - -```python -tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool] -``` - -Decorator to register a tool. - -Tools can optionally request a Context object by adding a parameter with the -Context type annotation. The context provides access to MCP capabilities like -logging, progress reporting, and resource access. - -This decorator supports multiple calling patterns: -- @server.tool (without parentheses) -- @server.tool (with empty parentheses) -- @server.tool("custom_name") (with name as first argument) -- @server.tool(name="custom_name") (with name as keyword argument) -- server.tool(function, name="custom_name") (direct function call) - -**Args:** -- `name_or_fn`: Either a function (when used as @tool), a string name, or None -- `name`: Optional name for the tool (keyword-only, alternative to name_or_fn) -- `description`: Optional description of what the tool does -- `tags`: Optional set of tags for categorizing the tool -- `output_schema`: Optional JSON schema for the tool's output -- `annotations`: Optional annotations about the tool's behavior -- `exclude_args`: Optional list of argument names to exclude from the tool schema. -Deprecated\: Use `Depends()` for dependency injection instead. -- `meta`: Optional meta information about the tool - -**Examples:** - -Register a tool with a custom name: -```python -@server.tool -def my_tool(x: int) -> str: - return str(x) - -# Register a tool with a custom name -@server.tool -def my_tool(x: int) -> str: - return str(x) - -@server.tool("custom_name") -def my_tool(x: int) -> str: - return str(x) - -@server.tool(name="custom_name") -def my_tool(x: int) -> str: - return str(x) - -# Direct function call -server.tool(my_function, name="custom_name") -``` - - -#### `add_resource` - -```python -add_resource(self, resource: Resource | Callable[..., Any]) -> Resource | ResourceTemplate -``` - -Add a resource to the server. - -**Args:** -- `resource`: A Resource instance or @resource-decorated function to add - -**Returns:** -- The resource instance that was added to the server. - - -#### `add_template` - -```python -add_template(self, template: ResourceTemplate) -> ResourceTemplate -``` - -Add a resource template to the server. - -**Args:** -- `template`: A ResourceTemplate instance to add - -**Returns:** -- The template instance that was added to the server. - - -#### `resource` - -```python -resource(self, uri: str) -> Callable[[F], F] -``` - -Decorator to register a function as a resource. - -The function will be called when the resource is read to generate its content. -The function can return: -- str for text content -- bytes for binary content -- other types will be converted to JSON - -Resources can optionally request a Context object by adding a parameter with the -Context type annotation. The context provides access to MCP capabilities like -logging, progress reporting, and session information. - -If the URI contains parameters (e.g. "resource://{param}") or the function -has parameters, it will be registered as a template resource. - -**Args:** -- `uri`: URI for the resource (e.g. "resource\://my-resource" or "resource\://{param}") -- `name`: Optional name for the resource -- `description`: Optional description of the resource -- `mime_type`: Optional MIME type for the resource -- `tags`: Optional set of tags for categorizing the resource -- `annotations`: Optional annotations about the resource's behavior -- `meta`: Optional meta information about the resource - -**Examples:** - -Register a resource with a custom name: -```python -@server.resource("resource://my-resource") -def get_data() -> str: - return "Hello, world!" - -@server.resource("resource://my-resource") -async get_data() -> str: - data = await fetch_data() - return f"Hello, world! {data}" - -@server.resource("resource://{city}/weather") -def get_weather(city: str) -> str: - return f"Weather for {city}" - -@server.resource("resource://{city}/weather") -async def get_weather_with_context(city: str, ctx: Context) -> str: - await ctx.info(f"Fetching weather for {city}") - return f"Weather for {city}" - -@server.resource("resource://{city}/weather") -async def get_weather(city: str) -> str: - data = await fetch_weather(city) - return f"Weather for {city}: {data}" -``` - - -#### `add_prompt` - -```python -add_prompt(self, prompt: Prompt | Callable[..., Any]) -> Prompt -``` - -Add a prompt to the server. - -**Args:** -- `prompt`: A Prompt instance or @prompt-decorated function to add - -**Returns:** -- The prompt instance that was added to the server. - - -#### `prompt` - -```python -prompt(self, name_or_fn: F) -> F -``` - -#### `prompt` - -```python -prompt(self, name_or_fn: str | None = None) -> Callable[[F], F] -``` - -#### `prompt` - -```python -prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt] -``` - -Decorator to register a prompt. - - Prompts can optionally request a Context object by adding a parameter with the - Context type annotation. The context provides access to MCP capabilities like - logging, progress reporting, and session information. - - This decorator supports multiple calling patterns: - - @server.prompt (without parentheses) - - @server.prompt() (with empty parentheses) - - @server.prompt("custom_name") (with name as first argument) - - @server.prompt(name="custom_name") (with name as keyword argument) - - server.prompt(function, name="custom_name") (direct function call) - - Args: - name_or_fn: Either a function (when used as @prompt), a string name, or None - name: Optional name for the prompt (keyword-only, alternative to name_or_fn) - description: Optional description of what the prompt does - tags: Optional set of tags for categorizing the prompt - meta: Optional meta information about the prompt - - Examples: - - ```python - @server.prompt - def analyze_table(table_name: str) -> list[Message]: - schema = read_table_schema(table_name) - return [ - { - "role": "user", - "content": f"Analyze this schema: -{schema}" - } - ] - - @server.prompt() - async def analyze_with_context(table_name: str, ctx: Context) -> list[Message]: - await ctx.info(f"Analyzing table {table_name}") - schema = read_table_schema(table_name) - return [ - { - "role": "user", - "content": f"Analyze this schema: -{schema}" - } - ] - - @server.prompt("custom_name") - async def analyze_file(path: str) -> list[Message]: - content = await read_file(path) - return [ - { - "role": "user", - "content": { - "type": "resource", - "resource": { - "uri": f"file://{path}", - "text": content - } - } - } - ] - - @server.prompt(name="custom_name") - def another_prompt(data: str) -> list[Message]: - return [{"role": "user", "content": data}] - - # Direct function call - server.prompt(my_function, name="custom_name") - ``` - - -#### `mount` - -```python -mount(self, server: FastMCP[LifespanResultT], namespace: str | None = None, as_proxy: bool | None = None, tool_names: dict[str, str] | None = None, prefix: str | None = None) -> None -``` - -Mount another FastMCP server on this server with an optional namespace. - -Unlike importing (with import_server), mounting establishes a dynamic connection -between servers. When a client interacts with a mounted server's objects through -the parent server, requests are forwarded to the mounted server in real-time. -This means changes to the mounted server are immediately reflected when accessed -through the parent. - -When a server is mounted with a namespace: -- Tools from the mounted server are accessible with namespaced names. - Example: If server has a tool named "get_weather", it will be available as "namespace_get_weather". -- Resources are accessible with namespaced URIs. - Example: If server has a resource with URI "weather://forecast", it will be available as - "weather://namespace/forecast". -- Templates are accessible with namespaced URI templates. - Example: If server has a template with URI "weather://location/{id}", it will be available - as "weather://namespace/location/{id}". -- Prompts are accessible with namespaced names. - Example: If server has a prompt named "weather_prompt", it will be available as - "namespace_weather_prompt". - -When a server is mounted without a namespace (namespace=None), its tools, resources, templates, -and prompts are accessible with their original names. Multiple servers can be mounted -without namespaces, and they will be tried in order until a match is found. - -The mounted server's lifespan is executed when the parent server starts, and its -middleware chain is invoked for all operations (tool calls, resource reads, prompts). - -**Args:** -- `server`: The FastMCP server to mount. -- `namespace`: Optional namespace to use for the mounted server's objects. If None, -the server's objects are accessible with their original names. -- `as_proxy`: Deprecated. Mounted servers now always have their lifespan and -middleware invoked. To create a proxy server, use create_proxy() -explicitly before mounting. -- `tool_names`: Optional mapping of original tool names to custom names. Use this -to override namespaced names. Keys are the original tool names from the -mounted server. -- `prefix`: Deprecated. Use namespace instead. - - -#### `import_server` - -```python -import_server(self, server: FastMCP[LifespanResultT], prefix: str | None = None) -> None -``` - -Import the MCP objects from another FastMCP server into this one, -optionally with a given prefix. - -.. deprecated:: - Use :meth:`mount` instead. ``import_server`` will be removed in a - future version. - -Note that when a server is *imported*, its objects are immediately -registered to the importing server. This is a one-time operation and -future changes to the imported server will not be reflected in the -importing server. Server-level configurations and lifespans are not imported. - -When a server is imported with a prefix: -- The tools are imported with prefixed names - Example: If server has a tool named "get_weather", it will be - available as "prefix_get_weather" -- The resources are imported with prefixed URIs using the new format - Example: If server has a resource with URI "weather://forecast", it will - be available as "weather://prefix/forecast" -- The templates are imported with prefixed URI templates using the new format - Example: If server has a template with URI "weather://location/{id}", it will - be available as "weather://prefix/location/{id}" -- The prompts are imported with prefixed names - Example: If server has a prompt named "weather_prompt", it will be available as - "prefix_weather_prompt" - -When a server is imported without a prefix (prefix=None), its tools, resources, -templates, and prompts are imported with their original names. - -**Args:** -- `server`: The FastMCP server to import -- `prefix`: Optional prefix to use for the imported server's objects. If None, -objects are imported with their original names. - - -#### `from_openapi` - -```python -from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient | None = None, name: str = 'OpenAPI Server', route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, validate_output: bool = True, **settings: Any) -> Self -``` - -Create a FastMCP server from an OpenAPI specification. - -**Args:** -- `openapi_spec`: OpenAPI schema as a dictionary -- `client`: Optional httpx AsyncClient for making HTTP requests. -If not provided, a default client is created using the first -server URL from the OpenAPI spec with a 30-second timeout. -- `name`: Name for the MCP server -- `route_maps`: Optional list of RouteMap objects defining route mappings -- `route_map_fn`: Optional callable for advanced route type mapping -- `mcp_component_fn`: Optional callable for component customization -- `mcp_names`: Optional dictionary mapping operationId to component names -- `tags`: Optional set of tags to add to all components -- `validate_output`: If True (default), tools use the output schema -extracted from the OpenAPI spec for response validation. If -False, a permissive schema is used instead, allowing any -response structure while still returning structured JSON. -- `**settings`: Additional settings passed to FastMCP - -**Returns:** -- A FastMCP server with an OpenAPIProvider attached. - - -#### `from_fastapi` - -```python -from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, httpx_client_kwargs: dict[str, Any] | None = None, tags: set[str] | None = None, **settings: Any) -> Self -``` - -Create a FastMCP server from a FastAPI application. - -**Args:** -- `app`: FastAPI application instance -- `name`: Name for the MCP server (defaults to app.title) -- `route_maps`: Optional list of RouteMap objects defining route mappings -- `route_map_fn`: Optional callable for advanced route type mapping -- `mcp_component_fn`: Optional callable for component customization -- `mcp_names`: Optional dictionary mapping operationId to component names -- `httpx_client_kwargs`: Optional kwargs passed to httpx.AsyncClient. -Use this to configure timeout and other client settings. -- `tags`: Optional set of tags to add to all components -- `**settings`: Additional settings passed to FastMCP - -**Returns:** -- A FastMCP server with an OpenAPIProvider attached. - - -#### `as_proxy` - -```python -as_proxy(cls, backend: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy -``` - -Create a FastMCP proxy server for the given backend. - -.. deprecated:: - Use :func:`fastmcp.server.create_proxy` instead. - This method will be removed in a future version. - -The `backend` argument can be either an existing `fastmcp.client.Client` -instance or any value accepted as the `transport` argument of -`fastmcp.client.Client`. This mirrors the convenience of the -`fastmcp.client.Client` constructor. - - -#### `generate_name` - -```python -generate_name(cls, name: str | None = None) -> str -``` diff --git a/docs/python-sdk/fastmcp-server-tasks-__init__.mdx b/docs/python-sdk/fastmcp-server-tasks-__init__.mdx deleted file mode 100644 index 9c9f5e88e..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-__init__.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.tasks` - - -MCP SEP-1686 background tasks support. - -This module implements protocol-level background task execution for MCP servers. - diff --git a/docs/python-sdk/fastmcp-server-tasks-capabilities.mdx b/docs/python-sdk/fastmcp-server-tasks-capabilities.mdx deleted file mode 100644 index 8e6ada03a..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-capabilities.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: capabilities -sidebarTitle: capabilities ---- - -# `fastmcp.server.tasks.capabilities` - - -SEP-1686 task capabilities declaration. - -## Functions - -### `get_task_capabilities` - -```python -get_task_capabilities() -> ServerTasksCapability | None -``` - - -Return the SEP-1686 task capabilities. - -Returns task capabilities as a first-class ServerCapabilities field, -declaring support for list, cancel, and request operations per SEP-1686. - -Returns None if a compatible pydocket is not installed (no task support). -Uses the canonical ``is_docket_available()`` check so that capability -advertisement and handler registration stay in sync — otherwise a server -with an old transitive pydocket would advertise task support and then -return "method not found" when clients invoked it. - -Note: prompts/resources are passed via extra_data since the SDK types -don't include them yet (FastMCP supports them ahead of the spec). - diff --git a/docs/python-sdk/fastmcp-server-tasks-config.mdx b/docs/python-sdk/fastmcp-server-tasks-config.mdx deleted file mode 100644 index a014e1ac4..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-config.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: config -sidebarTitle: config ---- - -# `fastmcp.server.tasks.config` - - -TaskConfig for MCP SEP-1686 background task execution modes. - -This module defines the configuration for how tools, resources, and prompts -handle task-augmented execution as specified in SEP-1686. - - -## Classes - -### `TaskMeta` - - -Metadata for task-augmented execution requests. - -When passed to call_tool/read_resource/get_prompt, signals that -the operation should be submitted as a background task. - -**Attributes:** -- `ttl`: Client-requested TTL in milliseconds. If None, uses server default. -- `fn_key`: Docket routing key. Auto-derived from component name if None. - - -### `TaskConfig` - - -Configuration for MCP background task execution (SEP-1686). - -Controls how a component handles task-augmented requests: - -- "forbidden": Component does not support task execution. Clients must not - request task augmentation; server returns -32601 if they do. -- "optional": Component supports both synchronous and task execution. - Client may request task augmentation or call normally. -- "required": Component requires task execution. Clients must request task - augmentation; server returns -32601 if they don't. - - -**Methods:** - -#### `from_bool` - -```python -from_bool(cls, value: bool) -> TaskConfig -``` - -Convert boolean task flag to TaskConfig. - -**Args:** -- `value`: True for "optional" mode, False for "forbidden" mode. - -**Returns:** -- TaskConfig with appropriate mode. - - -#### `supports_tasks` - -```python -supports_tasks(self) -> bool -``` - -Check if this component supports task execution. - -**Returns:** -- True if mode is "optional" or "required", False if "forbidden". - - -#### `validate_function` - -```python -validate_function(self, fn: Callable[..., Any], name: str) -> None -``` - -Validate that function is compatible with this task config. - -Task execution requires: -1. fastmcp[tasks] to be installed (pydocket) -2. Async functions - -Raises ImportError if mode is "optional" or "required" but pydocket -is not installed. Raises ValueError if function is synchronous. - -**Args:** -- `fn`: The function to validate (handles callable classes and staticmethods). -- `name`: Name for error messages. - -**Raises:** -- `ImportError`: If task execution is enabled but pydocket not installed. -- `ValueError`: If task execution is enabled but function is sync. - diff --git a/docs/python-sdk/fastmcp-server-tasks-context.mdx b/docs/python-sdk/fastmcp-server-tasks-context.mdx deleted file mode 100644 index 42f679ce7..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-context.mdx +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: context -sidebarTitle: context ---- - -# `fastmcp.server.tasks.context` - - -Task context and scoping for background task execution. - -Determines authorization scope (``get_task_scope``), manages the context -snapshot that is captured at task submission and restored in workers -(``TaskContextSnapshot``), and maintains in-process registries for live -sessions and servers. - - -## Functions - -### `get_task_scope` - -```python -get_task_scope() -> str | None -``` - - -Get the authorization scope for task isolation. - -Returns the raw scope identifier for the current access token, or -``None`` when no auth context is present (anonymous tasks). - -The scope is composed as ``client_id|sub`` when the token carries a -``sub`` claim — necessary for fixed-OAuth servers where ``client_id`` is -shared across all users — and falls back to ``client_id`` alone for -DCR/CIMD flows where the client identity is already per-user. - -Encoding for Redis/Docket keys happens at the boundary in ``keys.py``; -this function returns the raw value. - - -### `get_task_context` - -```python -get_task_context() -> TaskContextInfo | None -``` - - -Get the current task context if running inside a background task worker. - -This function extracts task information from the Docket execution context. -Returns None if not running in a task context (e.g., foreground execution). - -**Returns:** -- TaskContextInfo with task_id and task_scope, or None if not in a task. - - -### `get_task_session_id` - -```python -get_task_session_id() -> str | None -``` - - -Get the session_id for the current background task, if available. - -Reads the cached snapshot set by the worker-level restore dependency. -Returns None if not in a task context or the snapshot wasn't restored. - - -### `restore_task_snapshot` - -```python -restore_task_snapshot(key: str = TaskKey()) -> None -``` - - -Worker-level Docket dependency that restores the task-context snapshot. - -Runs before each fastmcp-owned task, populating the snapshot ContextVar -so user code — and any task-scoped dependency like ``_CurrentContext`` — -sees a ready snapshot without touching Redis itself. All Redis I/O -goes through Docket's async client, so cluster URLs and the memory:// -backend work transparently (#3897). Failures are non-fatal: the task -still runs, and sync helpers return ``None`` as they would have before -the snapshot was captured. - - -### `register_task_session` - -```python -register_task_session(session_id: str, session: ServerSession) -> None -``` - - -Register a session for in-process background task access. - -Called automatically when a task is submitted to Docket. The session is -stored as a weakref so it doesn't prevent garbage collection when the -client disconnects. - - -### `get_task_session` - -```python -get_task_session(session_id: str) -> ServerSession | None -``` - - -Get a registered session by ID if still alive. - -Returns None in distributed workers where the session lives in another -process — callers must handle this gracefully. - - -### `register_task_server` - -```python -register_task_server(task_id: str, server: FastMCP) -> None -``` - - -Register the server for a background task. - -Called at task-submission time so that background workers can resolve -the correct (child) server for mounted tasks. - - -### `get_task_server` - -```python -get_task_server(task_id: str) -> FastMCP | None -``` - - -Get the registered server for a background task, if still alive. - - -## Classes - -### `TaskContextInfo` - - -Information about the current background task context. - -Returned by ``get_task_context()`` when running inside a Docket worker. -Contains identifiers needed to communicate with the MCP session. - - -### `TaskContextSnapshot` - - -All context data snapshotted at task-submission time. - -Stored as a single Redis key per task, restored once in the worker. - - -**Methods:** - -#### `capture` - -```python -capture(cls) -> TaskContextSnapshot -``` - -Capture current context for background task execution. - - -#### `from_json` - -```python -from_json(cls, raw: str | bytes) -> TaskContextSnapshot -``` - -Deserialize from JSON stored in Redis. - - -#### `to_json` - -```python -to_json(self) -> str -``` - -Serialize to JSON for Redis storage. - - -#### `save` - -```python -save(self, docket: Docket, task_scope: str | None, task_id: str, ttl_seconds: int) -> None -``` - -Store this snapshot as a single Redis key. - diff --git a/docs/python-sdk/fastmcp-server-tasks-elicitation.mdx b/docs/python-sdk/fastmcp-server-tasks-elicitation.mdx deleted file mode 100644 index 3914d207c..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-elicitation.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: elicitation -sidebarTitle: elicitation ---- - -# `fastmcp.server.tasks.elicitation` - - -Background task elicitation support (SEP-1686). - -This module provides elicitation capabilities for background tasks running -in Docket workers. Unlike regular MCP requests, background tasks don't have -an active request context, so elicitation requires special handling: - -1. Set task status to "input_required" via Redis -2. Send notifications/tasks/status with elicitation metadata -3. Wait for client to send input via tasks/sendInput -4. Resume task execution with the provided input - -This uses the public MCP SDK APIs where possible, with minimal use of -internal APIs for background task coordination. - - -## Functions - -### `elicit_for_task` - -```python -elicit_for_task(task_id: str, session: ServerSession | None, message: str, schema: dict[str, Any], fastmcp: FastMCP) -> mcp.types.ElicitResult -``` - - -Send an elicitation request from a background task. - -This function handles the complexity of eliciting user input when running -in a Docket worker context where there's no active MCP request. - -**Args:** -- `task_id`: The background task ID -- `session`: The MCP ServerSession for this task -- `message`: The message to display to the user -- `schema`: The JSON schema for the expected response -- `fastmcp`: The FastMCP server instance - -**Returns:** -- ElicitResult containing the user's response - -**Raises:** -- `RuntimeError`: If Docket is not available -- `McpError`: If the elicitation request fails - - -### `relay_elicitation` - -```python -relay_elicitation(session: ServerSession, task_scope: str | None, task_id: str, elicitation: dict[str, Any], fastmcp: FastMCP) -> None -``` - - -Relay elicitation from a background task worker to the client. - -Called by the notification subscriber when it detects an input_required -notification with elicitation metadata. Sends a standard elicitation/create -request to the client session, then uses handle_task_input() to push the -response to Redis so the blocked worker can resume. - -**Args:** -- `session`: MCP ServerSession -- `task_scope`: Authorization scope for Redis key construction -- `task_id`: Background task ID -- `elicitation`: Elicitation metadata (message, requestedSchema) -- `fastmcp`: FastMCP server instance - - -### `handle_task_input` - -```python -handle_task_input(task_id: str, task_scope: str | None, action: str, content: dict[str, Any] | None, fastmcp: FastMCP) -> bool -``` - - -Handle input sent to a background task via tasks/sendInput. - -This is called when a client sends input in response to an elicitation -request from a background task. - -**Args:** -- `task_id`: The background task ID -- `task_scope`: Authorization scope for Redis key construction -- `action`: The elicitation action ("accept", "decline", "cancel") -- `content`: The response content (for "accept" action) -- `fastmcp`: The FastMCP server instance - -**Returns:** -- True if the input was successfully stored, False otherwise - diff --git a/docs/python-sdk/fastmcp-server-tasks-handlers.mdx b/docs/python-sdk/fastmcp-server-tasks-handlers.mdx deleted file mode 100644 index fd3659421..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-handlers.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: handlers -sidebarTitle: handlers ---- - -# `fastmcp.server.tasks.handlers` - - -SEP-1686 task execution handlers. - -Handles queuing tool/prompt/resource executions to Docket as background tasks. - - -## Functions - -### `submit_to_docket` - -```python -submit_to_docket(task_type: Literal['tool', 'resource', 'template', 'prompt'], key: str, component: Tool | Resource | ResourceTemplate | Prompt, arguments: dict[str, Any] | None = None, task_meta: TaskMeta | None = None) -> mcp.types.CreateTaskResult -``` - - -Submit any component to Docket for background execution (SEP-1686). - -Unified handler for all component types. Called by component's internal -methods (_run, _read, _render) when task metadata is present and mode allows. - -Queues the component's method to Docket, stores raw return values, -and converts to MCP types on retrieval. - -**Args:** -- `task_type`: Component type for task key construction -- `key`: The component key as seen by MCP layer (with namespace prefix) -- `component`: The component instance (Tool, Resource, ResourceTemplate, Prompt) -- `arguments`: Arguments/params (None for Resource which has no args) -- `task_meta`: Task execution metadata. If task_meta.ttl is provided, it -overrides the server default (docket.execution_ttl). - -**Returns:** -- Task stub with proper Task object - diff --git a/docs/python-sdk/fastmcp-server-tasks-keys.mdx b/docs/python-sdk/fastmcp-server-tasks-keys.mdx deleted file mode 100644 index a852fadd9..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-keys.mdx +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: keys -sidebarTitle: keys ---- - -# `fastmcp.server.tasks.keys` - - -Docket and Redis key encoding for background tasks. - -The compound Docket task key embeds the auth boundary so that the parser can -reject cross-scope access without consulting Redis. Authenticated and -anonymous tasks live in disjoint keyspaces: - - auth:{enc_scope}:{client_task_id}:{task_type}:{enc_identifier} - anon:{client_task_id}:{task_type}:{enc_identifier} - -The same `auth/anon` partition is used for the per-task Redis prefix -(``fastmcp:task:auth:{enc_scope}`` vs ``fastmcp:task:anon``) — see -``task_redis_prefix``. - -``task_scope`` is the raw scope identifier (typically derived from -``client_id`` or ``client_id|sub``); encoding happens once, at the boundary, -in this module. - - -## Functions - -### `build_task_key` - -```python -build_task_key(task_scope: str | None, client_task_id: str, task_type: str, component_identifier: str) -> str -``` - - -Build Docket task key with embedded metadata. - -When ``task_scope`` is ``None`` the task is anonymous and lives in the -``anon`` keyspace. Otherwise it lives under ``auth:{enc_scope}``. - -**Args:** -- `task_scope`: Raw authorization scope, or ``None`` for anonymous tasks -- `client_task_id`: Client-provided task ID -- `task_type`: Type of task ("tool", "prompt", "resource") -- `component_identifier`: Tool name, prompt name, or resource URI - -**Returns:** -- Encoded task key for Docket - -**Examples:** - ->>> build_task_key("client-a", "task456", "tool", "my_tool") -'auth:client-a:task456:tool:my_tool' ->>> build_task_key(None, "task456", "tool", "my_tool") -'anon:task456:tool:my_tool' ->>> build_task_key("client-a", "task456", "resource", "file://data.txt") -'auth:client-a:task456:resource:file%3A%2F%2Fdata.txt' - - -### `parse_task_key` - -```python -parse_task_key(task_key: str) -> TaskKeyParts -``` - - -Parse Docket task key to extract metadata. - -**Args:** -- `task_key`: Encoded task key from Docket - -**Returns:** -- Dict with keys: ``task_scope`` (``str | None``), ``client_task_id``, -- ``task_type``, ``component_identifier``. - -**Raises:** -- `ValueError`: If the key has an unrecognized tag or wrong segment count. - -**Examples:** - ->>> parse_task_key("auth:client-a:task456:tool:my_tool") -`{'task_scope': 'client-a', 'client_task_id': 'task456', 'task_type': 'tool', 'component_identifier': 'my_tool'}` ->>> parse_task_key("anon:task456:tool:my_tool") -`{'task_scope': None, 'client_task_id': 'task456', 'task_type': 'tool', 'component_identifier': 'my_tool'}` - - -### `get_client_task_id_from_key` - -```python -get_client_task_id_from_key(task_key: str) -> str -``` - - -Extract just the client task ID from a task key. - -**Args:** -- `task_key`: Full encoded task key - -**Returns:** -- Client-provided task ID - -**Examples:** - ->>> get_client_task_id_from_key("auth:client-a:task456:tool:my_tool") -'task456' ->>> get_client_task_id_from_key("anon:task456:tool:my_tool") -'task456' - - -### `task_redis_prefix` - -```python -task_redis_prefix(task_scope: str | None) -> str -``` - - -Return the Redis key prefix that owns a given scope. - -Authenticated tasks live under ``fastmcp:task:auth:{enc_scope}``; -anonymous tasks live under ``fastmcp:task:anon``. Callers append -``f":{task_id}:..."`` to compose the final key. - - -## Classes - -### `TaskKeyParts` - - -Decoded segments of a Docket task key. - -``task_scope`` is ``None`` for anonymous tasks, the raw scope string -otherwise. - diff --git a/docs/python-sdk/fastmcp-server-tasks-notifications.mdx b/docs/python-sdk/fastmcp-server-tasks-notifications.mdx deleted file mode 100644 index 441760f34..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-notifications.mdx +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: notifications -sidebarTitle: notifications ---- - -# `fastmcp.server.tasks.notifications` - - -Distributed notification queue for background task events (SEP-1686). - -Enables distributed Docket workers to send MCP notifications to clients -without holding session references. Workers push to a Redis queue, -the MCP server process subscribes and forwards to the client's session. - -Pattern: Fire-and-forward with retry -- One queue per session_id -- LPUSH/BRPOP for reliable ordered delivery -- Retry up to 3 times on delivery failure, then discard -- TTL-based expiration for stale messages - -Note: Docket's execution.subscribe() handles task state/progress events via -Redis Pub/Sub. This module handles elicitation-specific notifications that -require reliable delivery (input_required prompts, cancel signals). - - -## Functions - -### `push_notification` - -```python -push_notification(session_id: str, notification: dict[str, Any], docket: Docket) -> None -``` - - -Push notification to session's queue (called from Docket worker). - -Used for elicitation-specific notifications (input_required, cancel) -that need reliable delivery across distributed processes. - -**Args:** -- `session_id`: Target session's identifier -- `notification`: MCP notification dict (method, params, _meta) -- `docket`: Docket instance for Redis access - - -### `notification_subscriber_loop` - -```python -notification_subscriber_loop(session_id: str, session: ServerSession, docket: Docket, fastmcp: FastMCP) -> None -``` - - -Subscribe to notification queue and forward to session. - -Runs in the MCP server process. Bridges distributed workers to clients. - -This loop: -1. Maintains a heartbeat (active subscriber marker for debugging) -2. Blocks on BRPOP waiting for notifications -3. Forwards notifications to the client's session -4. Retries failed deliveries, then discards (no dead-letter queue) - -**Args:** -- `session_id`: Session identifier to subscribe to -- `session`: MCP ServerSession for sending notifications -- `docket`: Docket instance for Redis access -- `fastmcp`: FastMCP server instance (for elicitation relay) - - -### `ensure_subscriber_running` - -```python -ensure_subscriber_running(session_id: str, session: ServerSession, docket: Docket, fastmcp: FastMCP) -> None -``` - - -Start notification subscriber if not already running (idempotent). - -Subscriber is created on first task submission and cleaned up on disconnect. -Safe to call multiple times for the same session. - -**Args:** -- `session_id`: Session identifier -- `session`: MCP ServerSession -- `docket`: Docket instance -- `fastmcp`: FastMCP server instance (for elicitation relay) - - -### `stop_subscriber` - -```python -stop_subscriber(session_id: str) -> None -``` - - -Stop notification subscriber for a session. - -Called when session disconnects. Pending messages remain in queue -for delivery if client reconnects (with TTL expiration). - -**Args:** -- `session_id`: Session identifier - - -### `get_subscriber_count` - -```python -get_subscriber_count() -> int -``` - - -Get number of active subscribers (for monitoring). - diff --git a/docs/python-sdk/fastmcp-server-tasks-requests.mdx b/docs/python-sdk/fastmcp-server-tasks-requests.mdx deleted file mode 100644 index 64ac4a263..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-requests.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: requests -sidebarTitle: requests ---- - -# `fastmcp.server.tasks.requests` - - -SEP-1686 task request handlers. - -Handles MCP task protocol requests: tasks/get, tasks/result, tasks/list, tasks/cancel. -These handlers query and manage existing tasks (contrast with handlers.py which creates tasks). - -This module requires fastmcp[tasks] (pydocket). It is only imported when docket is available. - - -## Functions - -### `tasks_get_handler` - -```python -tasks_get_handler(server: FastMCP, params: dict[str, Any]) -> GetTaskResult -``` - - -Handle MCP 'tasks/get' request (SEP-1686). - -**Args:** -- `server`: FastMCP server instance -- `params`: Request params containing taskId - -**Returns:** -- Task status response with spec-compliant fields - - -### `tasks_result_handler` - -```python -tasks_result_handler(server: FastMCP, params: dict[str, Any]) -> Any -``` - - -Handle MCP 'tasks/result' request (SEP-1686). - -Converts raw task return values to MCP types based on task type. - -**Args:** -- `server`: FastMCP server instance -- `params`: Request params containing taskId - -**Returns:** -- MCP result (CallToolResult, GetPromptResult, or ReadResourceResult) - - -### `tasks_list_handler` - -```python -tasks_list_handler(server: FastMCP, params: dict[str, Any]) -> ListTasksResult -``` - - -Handle MCP 'tasks/list' request (SEP-1686). - -Note: With client-side tracking, this returns minimal info. - -**Args:** -- `server`: FastMCP server instance -- `params`: Request params (cursor, limit) - -**Returns:** -- Response with tasks list and pagination - - -### `tasks_cancel_handler` - -```python -tasks_cancel_handler(server: FastMCP, params: dict[str, Any]) -> CancelTaskResult -``` - - -Handle MCP 'tasks/cancel' request (SEP-1686). - -Cancels a running task, transitioning it to cancelled state. - -**Args:** -- `server`: FastMCP server instance -- `params`: Request params containing taskId - -**Returns:** -- Task status response showing cancelled state - diff --git a/docs/python-sdk/fastmcp-server-tasks-routing.mdx b/docs/python-sdk/fastmcp-server-tasks-routing.mdx deleted file mode 100644 index 435d62775..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-routing.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: routing -sidebarTitle: routing ---- - -# `fastmcp.server.tasks.routing` - - -Task routing helper for MCP components. - -Provides unified task mode enforcement and docket routing logic. - - -## Functions - -### `check_background_task` - -```python -check_background_task(component: Tool | Resource | ResourceTemplate | Prompt, task_type: TaskType, arguments: dict[str, Any] | None = None, task_meta: TaskMeta | None = None) -> mcp.types.CreateTaskResult | None -``` - - -Check task mode and submit to background if requested. - -**Args:** -- `component`: The MCP component -- `task_type`: Type of task ("tool", "resource", "template", "prompt") -- `arguments`: Arguments for tool/prompt/template execution -- `task_meta`: Task execution metadata. If provided, execute as background task. - -**Returns:** -- CreateTaskResult if submitted to docket, None for sync execution - -**Raises:** -- `McpError`: If mode="required" but no task metadata, or mode="forbidden" - but task metadata is present - diff --git a/docs/python-sdk/fastmcp-server-tasks-subscriptions.mdx b/docs/python-sdk/fastmcp-server-tasks-subscriptions.mdx deleted file mode 100644 index 2fd2e3cd4..000000000 --- a/docs/python-sdk/fastmcp-server-tasks-subscriptions.mdx +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: subscriptions -sidebarTitle: subscriptions ---- - -# `fastmcp.server.tasks.subscriptions` - - -Task subscription helpers for sending MCP notifications (SEP-1686). - -Subscribes to Docket execution state changes and sends notifications/tasks/status -to clients when their tasks change state. - -This module requires fastmcp[tasks] (pydocket). It is only imported when docket is available. - - -## Functions - -### `subscribe_to_task_updates` - -```python -subscribe_to_task_updates(task_id: str, task_key: str, session: ServerSession, docket: Docket, poll_interval_ms: int = 5000) -> None -``` - - -Subscribe to Docket execution events and send MCP notifications. - -Per SEP-1686 lines 436-444, servers MAY send notifications/tasks/status -when task state changes. This is an optional optimization that reduces -client polling frequency. - -**Args:** -- `task_id`: Client-visible task ID (server-generated UUID) -- `task_key`: Internal Docket execution key (includes session, type, component) -- `session`: MCP ServerSession for sending notifications -- `docket`: Docket instance for subscribing to execution events -- `poll_interval_ms`: Poll interval in milliseconds to include in notifications - diff --git a/docs/python-sdk/fastmcp-server-telemetry.mdx b/docs/python-sdk/fastmcp-server-telemetry.mdx deleted file mode 100644 index 6e0b44ba9..000000000 --- a/docs/python-sdk/fastmcp-server-telemetry.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: telemetry -sidebarTitle: telemetry ---- - -# `fastmcp.server.telemetry` - - -Server-side telemetry helpers. - -## Functions - -### `get_auth_span_attributes` - -```python -get_auth_span_attributes() -> dict[str, str] -``` - - -Get auth attributes for the current request, if authenticated. - - -### `get_session_span_attributes` - -```python -get_session_span_attributes() -> dict[str, str] -``` - - -Get session attributes for the current request. - - -### `server_span` - -```python -server_span(name: str, method: str, server_name: str, component_type: str, component_key: str, resource_uri: str | None = None, tool_name: str | None = None, prompt_name: str | None = None) -> Generator[Span, None, None] -``` - - -Create a SERVER span with standard MCP attributes and auth context. - -Automatically records any exception on the span and sets error status. - - -### `delegate_span` - -```python -delegate_span(name: str, provider_type: str, component_key: str, method: str | None = None) -> Generator[Span, None, None] -``` - - -Create an INTERNAL span for provider delegation. - -Used by FastMCPProvider when delegating to mounted servers. -Automatically records any exception on the span and sets error status. - diff --git a/docs/python-sdk/fastmcp-server-transforms-__init__.mdx b/docs/python-sdk/fastmcp-server-transforms-__init__.mdx deleted file mode 100644 index f98150302..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-__init__.mdx +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.transforms` - - -Transform system for component transformations. - -Transforms modify components (tools, resources, prompts). List operations use a pure -function pattern where transforms receive sequences and return transformed sequences. -Get operations use a middleware pattern with `call_next` to chain lookups. - -Unlike middleware (which operates on requests), transforms are observable by the -system for task registration, tag filtering, and component introspection. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.transforms import Namespace - - server = FastMCP("Server") - mount = server.mount(other_server) - mount.add_transform(Namespace("api")) # Tools become api_toolname - ``` - - -## Classes - -### `GetToolNext` - - -Protocol for get_tool call_next functions. - - -### `GetResourceNext` - - -Protocol for get_resource call_next functions. - - -### `GetResourceTemplateNext` - - -Protocol for get_resource_template call_next functions. - - -### `GetPromptNext` - - -Protocol for get_prompt call_next functions. - - -### `Transform` - - -Base class for component transformations. - -List operations use a pure function pattern: transforms receive sequences -and return transformed sequences. Get operations use a middleware pattern -with `call_next` to chain lookups. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -List tools with transformation applied. - -**Args:** -- `tools`: Sequence of tools to transform. - -**Returns:** -- Transformed sequence of tools. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Get a tool by name. - -**Args:** -- `name`: The requested tool name (may be transformed). -- `call_next`: Callable to get tool from downstream. -- `version`: Optional version filter to apply. - -**Returns:** -- The tool if found, None otherwise. - - -#### `list_resources` - -```python -list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource] -``` - -List resources with transformation applied. - -**Args:** -- `resources`: Sequence of resources to transform. - -**Returns:** -- Transformed sequence of resources. - - -#### `get_resource` - -```python -get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None -``` - -Get a resource by URI. - -**Args:** -- `uri`: The requested resource URI (may be transformed). -- `call_next`: Callable to get resource from downstream. -- `version`: Optional version filter to apply. - -**Returns:** -- The resource if found, None otherwise. - - -#### `list_resource_templates` - -```python -list_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate] -``` - -List resource templates with transformation applied. - -**Args:** -- `templates`: Sequence of resource templates to transform. - -**Returns:** -- Transformed sequence of resource templates. - - -#### `get_resource_template` - -```python -get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> ResourceTemplate | None -``` - -Get a resource template by URI. - -**Args:** -- `uri`: The requested template URI (may be transformed). -- `call_next`: Callable to get template from downstream. -- `version`: Optional version filter to apply. - -**Returns:** -- The resource template if found, None otherwise. - - -#### `list_prompts` - -```python -list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt] -``` - -List prompts with transformation applied. - -**Args:** -- `prompts`: Sequence of prompts to transform. - -**Returns:** -- Transformed sequence of prompts. - - -#### `get_prompt` - -```python -get_prompt(self, name: str, call_next: GetPromptNext) -> Prompt | None -``` - -Get a prompt by name. - -**Args:** -- `name`: The requested prompt name (may be transformed). -- `call_next`: Callable to get prompt from downstream. -- `version`: Optional version filter to apply. - -**Returns:** -- The prompt if found, None otherwise. - diff --git a/docs/python-sdk/fastmcp-server-transforms-catalog.mdx b/docs/python-sdk/fastmcp-server-transforms-catalog.mdx deleted file mode 100644 index 5728d65b1..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-catalog.mdx +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: catalog -sidebarTitle: catalog ---- - -# `fastmcp.server.transforms.catalog` - - -Base class for transforms that need to read the real component catalog. - -Some transforms replace ``list_tools()`` output with synthetic components -(e.g. a search interface) while still needing access to the *real* -(auth-filtered) catalog at call time. ``CatalogTransform`` provides the -bypass machinery so subclasses can call ``get_tool_catalog()`` without -triggering their own replacement logic. - -Re-entrancy problem -------------------- - -When a synthetic tool handler calls ``get_tool_catalog()``, that calls -``ctx.fastmcp.list_tools()`` which re-enters the transform pipeline — -including *this* transform's ``list_tools()``. If the subclass overrides -``list_tools()`` directly, the re-entrant call would hit the subclass's -replacement logic again (returning synthetic tools instead of the real -catalog). A ``super()`` call can't prevent this because Python can't -short-circuit a method after ``super()`` returns. - -Solution: ``CatalogTransform`` owns ``list_tools()`` and uses a -per-instance ``ContextVar`` to detect re-entrant calls. During bypass, -it passes through to the base ``Transform.list_tools()`` (a no-op). -Otherwise, it delegates to ``transform_tools()`` — the subclass hook -where replacement logic lives. Same pattern for resources, prompts, -and resource templates. - -This is *not* the same as the ``Provider._list_tools()`` convention -(which produces raw components with no arguments). ``transform_tools()`` -receives the current catalog and returns a transformed version. The -distinct name avoids confusion between the two patterns. - -Usage:: - - class MyTransform(CatalogTransform): - async def transform_tools(self, tools): - return [self._make_search_tool()] - - def _make_search_tool(self): - async def search(ctx: Context = None): - real_tools = await self.get_tool_catalog(ctx) - ... - return Tool.from_function(fn=search, name="search") - - -## Classes - -### `CatalogTransform` - - -Transform that needs access to the real component catalog. - -Subclasses override ``transform_tools()`` / ``transform_resources()`` -/ ``transform_prompts()`` / ``transform_resource_templates()`` -instead of the ``list_*()`` methods. The base class owns -``list_*()`` and handles re-entrant bypass automatically — subclasses -never see re-entrant calls from ``get_*_catalog()``. - -The ``get_*_catalog()`` methods fetch the real (auth-filtered) catalog -by temporarily setting a bypass flag so that this transform's -``list_*()`` passes through without calling the subclass hook. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -#### `list_resources` - -```python -list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource] -``` - -#### `list_resource_templates` - -```python -list_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate] -``` - -#### `list_prompts` - -```python -list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt] -``` - -#### `transform_tools` - -```python -transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Transform the tool catalog. - -Override this method to replace, filter, or augment the tool listing. -The default implementation passes through unchanged. - -Do NOT override ``list_tools()`` directly — the base class uses it -to handle re-entrant bypass when ``get_tool_catalog()`` reads the -real catalog. - - -#### `transform_resources` - -```python -transform_resources(self, resources: Sequence[Resource]) -> Sequence[Resource] -``` - -Transform the resource catalog. - -Override this method to replace, filter, or augment the resource listing. -The default implementation passes through unchanged. - -Do NOT override ``list_resources()`` directly — the base class uses it -to handle re-entrant bypass when ``get_resource_catalog()`` reads the -real catalog. - - -#### `transform_resource_templates` - -```python -transform_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate] -``` - -Transform the resource template catalog. - -Override this method to replace, filter, or augment the template listing. -The default implementation passes through unchanged. - -Do NOT override ``list_resource_templates()`` directly — the base class -uses it to handle re-entrant bypass when -``get_resource_template_catalog()`` reads the real catalog. - - -#### `transform_prompts` - -```python -transform_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt] -``` - -Transform the prompt catalog. - -Override this method to replace, filter, or augment the prompt listing. -The default implementation passes through unchanged. - -Do NOT override ``list_prompts()`` directly — the base class uses it -to handle re-entrant bypass when ``get_prompt_catalog()`` reads the -real catalog. - - -#### `get_tool_catalog` - -```python -get_tool_catalog(self, ctx: Context) -> Sequence[Tool] -``` - -Fetch the real tool catalog, bypassing this transform. - -The result is deduplicated by name so that only the highest version -of each tool is returned — matching what protocol handlers expose -on the wire. - -**Args:** -- `ctx`: The current request context. -- `run_middleware`: Whether to run middleware on the inner call. -Defaults to True because this is typically called from a -tool handler where list_tools middleware has not yet run. - - -#### `get_resource_catalog` - -```python -get_resource_catalog(self, ctx: Context) -> Sequence[Resource] -``` - -Fetch the real resource catalog, bypassing this transform. - -**Args:** -- `ctx`: The current request context. -- `run_middleware`: Whether to run middleware on the inner call. -Defaults to True because this is typically called from a -tool handler where list_resources middleware has not yet run. - - -#### `get_prompt_catalog` - -```python -get_prompt_catalog(self, ctx: Context) -> Sequence[Prompt] -``` - -Fetch the real prompt catalog, bypassing this transform. - -**Args:** -- `ctx`: The current request context. -- `run_middleware`: Whether to run middleware on the inner call. -Defaults to True because this is typically called from a -tool handler where list_prompts middleware has not yet run. - - -#### `get_resource_template_catalog` - -```python -get_resource_template_catalog(self, ctx: Context) -> Sequence[ResourceTemplate] -``` - -Fetch the real resource template catalog, bypassing this transform. - -**Args:** -- `ctx`: The current request context. -- `run_middleware`: Whether to run middleware on the inner call. -Defaults to True because this is typically called from a -tool handler where list_resource_templates middleware has -not yet run. - diff --git a/docs/python-sdk/fastmcp-server-transforms-namespace.mdx b/docs/python-sdk/fastmcp-server-transforms-namespace.mdx deleted file mode 100644 index 9f590356d..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-namespace.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: namespace -sidebarTitle: namespace ---- - -# `fastmcp.server.transforms.namespace` - - -Namespace transform for prefixing component names. - -## Classes - -### `Namespace` - - -Prefixes component names with a namespace. - -- Tools: name → namespace_name -- Prompts: name → namespace_name -- Resources: protocol://path → protocol://namespace/path -- Resource Templates: same as resources - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Prefix tool names with namespace. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Get tool by namespaced name. - - -#### `list_resources` - -```python -list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource] -``` - -Add namespace path segment to resource URIs. - - -#### `get_resource` - -```python -get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None -``` - -Get resource by namespaced URI. - - -#### `list_resource_templates` - -```python -list_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate] -``` - -Add namespace path segment to template URIs. - - -#### `get_resource_template` - -```python -get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> ResourceTemplate | None -``` - -Get resource template by namespaced URI. - - -#### `list_prompts` - -```python -list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt] -``` - -Prefix prompt names with namespace. - - -#### `get_prompt` - -```python -get_prompt(self, name: str, call_next: GetPromptNext) -> Prompt | None -``` - -Get prompt by namespaced name. - diff --git a/docs/python-sdk/fastmcp-server-transforms-prompts_as_tools.mdx b/docs/python-sdk/fastmcp-server-transforms-prompts_as_tools.mdx deleted file mode 100644 index dc3b659d0..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-prompts_as_tools.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: prompts_as_tools -sidebarTitle: prompts_as_tools ---- - -# `fastmcp.server.transforms.prompts_as_tools` - - -Transform that exposes prompts as tools. - -This transform generates tools for listing and getting prompts, enabling -clients that only support tools to access prompt functionality. - -The generated tools route through `ctx.fastmcp` at runtime, so all server -middleware (auth, visibility, rate limiting, etc.) applies to prompt -operations exactly as it would for direct `prompts/get` calls. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.transforms import PromptsAsTools - - mcp = FastMCP("Server") - mcp.add_transform(PromptsAsTools(mcp)) - # Now has list_prompts and get_prompt tools - ``` - - -## Classes - -### `PromptsAsTools` - - -Transform that adds tools for listing and getting prompts. - -Generates two tools: -- `list_prompts`: Lists all prompts -- `get_prompt`: Gets a specific prompt with optional arguments - -The generated tools route through the server at runtime, so auth, -middleware, and visibility apply automatically. - -This transform should be applied to a FastMCP server instance, not -a raw Provider, because the generated tools need the server's -middleware chain for auth and visibility filtering. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Add prompt tools to the tool list. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Get a tool by name, including generated prompt tools. - diff --git a/docs/python-sdk/fastmcp-server-transforms-resources_as_tools.mdx b/docs/python-sdk/fastmcp-server-transforms-resources_as_tools.mdx deleted file mode 100644 index 50f0a0c95..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-resources_as_tools.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: resources_as_tools -sidebarTitle: resources_as_tools ---- - -# `fastmcp.server.transforms.resources_as_tools` - - -Transform that exposes resources as tools. - -This transform generates tools for listing and reading resources, enabling -clients that only support tools to access resource functionality. - -The generated tools route through `ctx.fastmcp` at runtime, so all server -middleware (auth, visibility, rate limiting, etc.) applies to resource -operations exactly as it would for direct `resources/read` calls. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.transforms import ResourcesAsTools - - mcp = FastMCP("Server") - mcp.add_transform(ResourcesAsTools(mcp)) - # Now has list_resources and read_resource tools - ``` - - -## Classes - -### `ResourcesAsTools` - - -Transform that adds tools for listing and reading resources. - -Generates two tools: -- `list_resources`: Lists all resources and templates -- `read_resource`: Reads a resource by URI - -The generated tools route through the server at runtime, so auth, -middleware, and visibility apply automatically. - -This transform should be applied to a FastMCP server instance, not -a raw Provider, because the generated tools need the server's -middleware chain for auth and visibility filtering. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Add resource tools to the tool list. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Get a tool by name, including generated resource tools. - diff --git a/docs/python-sdk/fastmcp-server-transforms-search-__init__.mdx b/docs/python-sdk/fastmcp-server-transforms-search-__init__.mdx deleted file mode 100644 index 80b71d226..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-search-__init__.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: __init__ -sidebarTitle: __init__ ---- - -# `fastmcp.server.transforms.search` - - -Search transforms for tool discovery. - -Search transforms collapse a large tool catalog into a search interface, -letting LLMs discover tools on demand instead of seeing the full list. - -Example: - ```python - from fastmcp import FastMCP - from fastmcp.server.transforms.search import RegexSearchTransform - - mcp = FastMCP("Server") - mcp.add_transform(RegexSearchTransform()) - # list_tools now returns only search_tools + call_tool - ``` - diff --git a/docs/python-sdk/fastmcp-server-transforms-search-base.mdx b/docs/python-sdk/fastmcp-server-transforms-search-base.mdx deleted file mode 100644 index 7ecd3b5f2..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-search-base.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: base -sidebarTitle: base ---- - -# `fastmcp.server.transforms.search.base` - - -Base class for search transforms. - -Search transforms replace ``list_tools()`` output with a small set of -synthetic tools — a search tool and a call-tool proxy — so LLMs can -discover tools on demand instead of receiving the full catalog. - -All concrete search transforms (``RegexSearchTransform``, -``BM25SearchTransform``, etc.) inherit from ``BaseSearchTransform`` and -implement ``_make_search_tool()`` and ``_search()`` to provide their -specific search strategy. - -Example:: - - from fastmcp import FastMCP - from fastmcp.server.transforms.search import RegexSearchTransform - - mcp = FastMCP("Server") - - @mcp.tool - def add(a: int, b: int) -> int: ... - - @mcp.tool - def multiply(x: float, y: float) -> float: ... - - # Clients now see only ``search_tools`` and ``call_tool``. - # The original tools are discoverable via search. - mcp.add_transform(RegexSearchTransform()) - - -## Functions - -### `serialize_tools_for_output_json` - -```python -serialize_tools_for_output_json(tools: Sequence[Tool]) -> list[dict[str, Any]] -``` - - -Serialize tools to the same dict format as ``list_tools`` output. - - -### `serialize_tools_for_output_markdown` - -```python -serialize_tools_for_output_markdown(tools: Sequence[Tool]) -> str -``` - - -Serialize tools to compact markdown, using ~65-70% fewer tokens than JSON. - - -## Classes - -### `BaseSearchTransform` - - -Replace the tool listing with a search interface. - -When this transform is active, ``list_tools()`` returns only: - -* Any tools listed in ``always_visible`` (pinned). -* A **search tool** that finds tools matching a query. -* A **call_tool** proxy that executes tools discovered via search. - -Hidden tools remain callable — ``get_tool()`` delegates unknown -names downstream, so direct calls and the call-tool proxy both work. - -Search results respect the full auth pipeline: middleware, visibility -transforms, and component-level auth checks all apply. - -**Args:** -- `max_results`: Maximum number of tools returned per search. -- `always_visible`: Tool names that stay in the ``list_tools`` -output alongside the synthetic search/call tools. -- `search_tool_name`: Name of the generated search tool. -- `call_tool_name`: Name of the generated call-tool proxy. - - -**Methods:** - -#### `transform_tools` - -```python -transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Replace the catalog with pinned + synthetic search/call tools. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Intercept synthetic tool names; delegate everything else. - diff --git a/docs/python-sdk/fastmcp-server-transforms-search-bm25.mdx b/docs/python-sdk/fastmcp-server-transforms-search-bm25.mdx deleted file mode 100644 index d5264f46a..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-search-bm25.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: bm25 -sidebarTitle: bm25 ---- - -# `fastmcp.server.transforms.search.bm25` - - -BM25-based search transform. - -## Classes - -### `BM25SearchTransform` - - -Search transform using BM25 Okapi relevance ranking. - -Maintains an in-memory index that is lazily rebuilt when the tool -catalog changes (detected via a hash of tool names). - diff --git a/docs/python-sdk/fastmcp-server-transforms-search-regex.mdx b/docs/python-sdk/fastmcp-server-transforms-search-regex.mdx deleted file mode 100644 index e36c8d25e..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-search-regex.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: regex -sidebarTitle: regex ---- - -# `fastmcp.server.transforms.search.regex` - - -Regex-based search transform. - -## Classes - -### `RegexSearchTransform` - - -Search transform using regex pattern matching. - -Tools are matched against their name, description, and parameter -information using ``re.search`` with ``re.IGNORECASE``. - diff --git a/docs/python-sdk/fastmcp-server-transforms-tool_transform.mdx b/docs/python-sdk/fastmcp-server-transforms-tool_transform.mdx deleted file mode 100644 index d911f4819..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-tool_transform.mdx +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: tool_transform -sidebarTitle: tool_transform ---- - -# `fastmcp.server.transforms.tool_transform` - - -Transform for applying tool transformations. - -## Classes - -### `ToolTransform` - - -Applies tool transformations to modify tool schemas. - -Wraps ToolTransformConfig to apply argument renames, schema changes, -hidden arguments, and other transformations at the transform level. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Apply transforms to matching tools. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Get tool by transformed name. - diff --git a/docs/python-sdk/fastmcp-server-transforms-version_filter.mdx b/docs/python-sdk/fastmcp-server-transforms-version_filter.mdx deleted file mode 100644 index 7902c0a0a..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-version_filter.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: version_filter -sidebarTitle: version_filter ---- - -# `fastmcp.server.transforms.version_filter` - - -Version filter transform for filtering components by version range. - -## Classes - -### `VersionFilter` - - -Filters components by version range. - -When applied to a provider or server, components within the version range -are visible, and unversioned components are included by default. Within -that filtered set, the highest version of each component is exposed to -clients (standard deduplication behavior). Set -``include_unversioned=False`` to exclude unversioned components. - -Parameters mirror comparison operators for clarity: - - # Versions < 3.0 (v1 and v2) - server.add_transform(VersionFilter(version_lt="3.0")) - - # Versions >= 2.0 and < 3.0 (only v2.x) - server.add_transform(VersionFilter(version_gte="2.0", version_lt="3.0")) - -Works with any version string - PEP 440 (1.0, 2.0) or dates (2025-01-01). - -**Args:** -- `version_gte`: Versions >= this value pass through. -- `version_lt`: Versions < this value pass through. -- `include_unversioned`: Whether unversioned components (``version=None``) -should pass through the filter. Defaults to True. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -#### `list_resources` - -```python -list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource] -``` - -#### `get_resource` - -```python -get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None -``` - -#### `list_resource_templates` - -```python -list_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate] -``` - -#### `get_resource_template` - -```python -get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> ResourceTemplate | None -``` - -#### `list_prompts` - -```python -list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt] -``` - -#### `get_prompt` - -```python -get_prompt(self, name: str, call_next: GetPromptNext) -> Prompt | None -``` diff --git a/docs/python-sdk/fastmcp-server-transforms-visibility.mdx b/docs/python-sdk/fastmcp-server-transforms-visibility.mdx deleted file mode 100644 index 772cddc97..000000000 --- a/docs/python-sdk/fastmcp-server-transforms-visibility.mdx +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: visibility -sidebarTitle: visibility ---- - -# `fastmcp.server.transforms.visibility` - - -Visibility transform for marking component visibility state. - -Each Visibility instance marks components via internal metadata. Multiple -visibility transforms can be stacked - later transforms override earlier ones. -Final filtering happens at the Provider level. - - -## Functions - -### `is_enabled` - -```python -is_enabled(component: FastMCPComponent) -> bool -``` - - -Check if component is enabled. - -Returns True if: -- No visibility mark exists (default is enabled) -- Visibility mark is True - -Returns False if visibility mark is False. - -**Args:** -- `component`: Component to check. - -**Returns:** -- True if component should be enabled/visible to clients. - - -### `get_visibility_rules` - -```python -get_visibility_rules(context: Context) -> list[dict[str, Any]] -``` - - -Load visibility rule dicts from session state. - - -### `save_visibility_rules` - -```python -save_visibility_rules(context: Context, rules: list[dict[str, Any]]) -> None -``` - - -Save visibility rule dicts to session state and send notifications. - -**Args:** -- `context`: The context to save rules for. -- `rules`: The visibility rules to save. -- `components`: Optional hint about which component types are affected. -If None, sends notifications for all types (safe default). -If provided, only sends notifications for specified types. - - -### `create_visibility_transforms` - -```python -create_visibility_transforms(rules: list[dict[str, Any]]) -> list[Visibility] -``` - - -Convert rule dicts to Visibility transforms. - - -### `get_session_transforms` - -```python -get_session_transforms(context: Context) -> list[Visibility] -``` - - -Get session-specific Visibility transforms from state store. - - -### `enable_components` - -```python -enable_components(context: Context) -> None -``` - - -Enable components matching criteria for this session only. - -Session rules override global transforms. Rules accumulate - each call -adds a new rule to the session. Later marks override earlier ones -(Visibility transform semantics). - -Sends notifications to this session only: ToolListChangedNotification, -ResourceListChangedNotification, and PromptListChangedNotification. - -**Args:** -- `context`: The context for this session. -- `names`: Component names or URIs to match. -- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}). -- `version`: Component version spec to match. -- `tags`: Tags to match (component must have at least one). -- `components`: Component types to match (e.g., {"tool", "prompt"}). -- `match_all`: If True, matches all components regardless of other criteria. - - -### `disable_components` - -```python -disable_components(context: Context) -> None -``` - - -Disable components matching criteria for this session only. - -Session rules override global transforms. Rules accumulate - each call -adds a new rule to the session. Later marks override earlier ones -(Visibility transform semantics). - -Sends notifications to this session only: ToolListChangedNotification, -ResourceListChangedNotification, and PromptListChangedNotification. - -**Args:** -- `context`: The context for this session. -- `names`: Component names or URIs to match. -- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}). -- `version`: Component version spec to match. -- `tags`: Tags to match (component must have at least one). -- `components`: Component types to match (e.g., {"tool", "prompt"}). -- `match_all`: If True, matches all components regardless of other criteria. - - -### `reset_visibility` - -```python -reset_visibility(context: Context) -> None -``` - - -Clear all session visibility rules. - -Use this to reset session visibility back to global defaults. - -Sends notifications to this session only: ToolListChangedNotification, -ResourceListChangedNotification, and PromptListChangedNotification. - -**Args:** -- `context`: The context for this session. - - -### `apply_session_transforms` - -```python -apply_session_transforms(components: Sequence[ComponentT]) -> Sequence[ComponentT] -``` - - -Apply session-specific visibility transforms to components. - -This helper applies session-level enable/disable rules by marking -components with their visibility state. Session transforms override -global transforms due to mark-based semantics (later marks win). - -**Args:** -- `components`: The components to apply session transforms to. - -**Returns:** -- The components with session transforms applied. - - -## Classes - -### `Visibility` - - -Sets visibility state on matching components. - -Does NOT filter inline - just marks components with visibility state. -Later transforms in the chain can override earlier marks. -Final filtering happens at the Provider level after all transforms run. - - -**Methods:** - -#### `list_tools` - -```python -list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool] -``` - -Mark tools by visibility state. - - -#### `get_tool` - -```python -get_tool(self, name: str, call_next: GetToolNext) -> Tool | None -``` - -Mark tool if found. - - -#### `list_resources` - -```python -list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource] -``` - -Mark resources by visibility state. - - -#### `get_resource` - -```python -get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None -``` - -Mark resource if found. - - -#### `list_resource_templates` - -```python -list_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate] -``` - -Mark resource templates by visibility state. - - -#### `get_resource_template` - -```python -get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> ResourceTemplate | None -``` - -Mark resource template if found. - - -#### `list_prompts` - -```python -list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt] -``` - -Mark prompts by visibility state. - - -#### `get_prompt` - -```python -get_prompt(self, name: str, call_next: GetPromptNext) -> Prompt | None -``` - -Mark prompt if found. - diff --git a/docs/python-sdk/fastmcp-server-__init__.mdx b/docs/python-sdk/fastmcp-server.mdx similarity index 72% rename from docs/python-sdk/fastmcp-server-__init__.mdx rename to docs/python-sdk/fastmcp-server.mdx index 157a018ce..589fdadac 100644 --- a/docs/python-sdk/fastmcp-server-__init__.mdx +++ b/docs/python-sdk/fastmcp-server.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: server +sidebarTitle: server --- # `fastmcp.server` diff --git a/docs/python-sdk/fastmcp-settings.mdx b/docs/python-sdk/fastmcp-settings.mdx index f9b0cf26a..87940be01 100644 --- a/docs/python-sdk/fastmcp-settings.mdx +++ b/docs/python-sdk/fastmcp-settings.mdx @@ -7,13 +7,13 @@ sidebarTitle: settings ## Classes -### `DocketSettings` +### `DocketSettings` Docket worker configuration. -### `Settings` +### `Settings` FastMCP settings. @@ -21,7 +21,7 @@ FastMCP settings. **Methods:** -#### `get_setting` +#### `get_setting` ```python get_setting(self, attr: str) -> Any @@ -31,7 +31,7 @@ Get a setting. If the setting contains one or more `__`, it will be treated as a nested setting. -#### `set_setting` +#### `set_setting` ```python set_setting(self, attr: str, value: Any) -> None @@ -41,7 +41,7 @@ Set a setting. If the setting contains one or more `__`, it will be treated as a nested setting. -#### `normalize_log_level` +#### `normalize_log_level` ```python normalize_log_level(cls, v) diff --git a/docs/python-sdk/fastmcp-telemetry.mdx b/docs/python-sdk/fastmcp-telemetry.mdx index 757e41fb9..44d68cb78 100644 --- a/docs/python-sdk/fastmcp-telemetry.mdx +++ b/docs/python-sdk/fastmcp-telemetry.mdx @@ -31,7 +31,7 @@ Example usage with SDK: ## Functions -### `get_tracer` +### `get_tracer` ```python get_tracer(version: str | None = None) -> Tracer @@ -47,7 +47,7 @@ Get the FastMCP tracer for creating spans. - A tracer instance. Returns a no-op tracer if no SDK is configured. -### `inject_trace_context` +### `inject_trace_context` ```python inject_trace_context(meta: dict[str, Any] | None = None) -> dict[str, Any] | None @@ -64,7 +64,7 @@ Inject current trace context into a meta dict for MCP request propagation. - or None if no trace context to inject and meta was None -### `record_span_error` +### `record_span_error` ```python record_span_error(span: Span, exception: BaseException) -> None @@ -74,7 +74,7 @@ record_span_error(span: Span, exception: BaseException) -> None Record an exception on a span and set error status. -### `extract_trace_context` +### `extract_trace_context` ```python extract_trace_context(meta: dict[str, Any] | None) -> Context diff --git a/docs/python-sdk/fastmcp-tools-base.mdx b/docs/python-sdk/fastmcp-tools-base.mdx deleted file mode 100644 index 0123949a2..000000000 --- a/docs/python-sdk/fastmcp-tools-base.mdx +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: base -sidebarTitle: base ---- - -# `fastmcp.tools.base` - -## Functions - -### `default_serializer` - -```python -default_serializer(data: Any) -> str -``` - -## Classes - -### `ToolResult` - -**Methods:** - -#### `to_mcp_result` - -```python -to_mcp_result(self) -> list[ContentBlock] | tuple[list[ContentBlock], dict[str, Any]] | CallToolResult -``` - -### `Tool` - - -Internal tool registration info. - - -**Methods:** - -#### `to_mcp_tool` - -```python -to_mcp_tool(self, **overrides: Any) -> MCPTool -``` - -Convert the FastMCP tool to an MCP tool. - - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any]) -> FunctionTool -``` - -Create a Tool from a function. - - -#### `run` - -```python -run(self, arguments: dict[str, Any]) -> ToolResult -``` - -Run the tool with arguments. - -This method is not implemented in the base Tool class and must be -implemented by subclasses. - -`run()` can EITHER return a list of ContentBlocks, or a tuple of -(list of ContentBlocks, dict of structured output). - - -#### `convert_result` - -```python -convert_result(self, raw_value: Any) -> ToolResult -``` - -Convert a raw result to ToolResult. - -Handles ToolResult passthrough and converts raw values using the tool's -attributes (serializer, output_schema) for proper conversion. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this tool with docket for background execution. - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, arguments: dict[str, Any], **kwargs: Any) -> Execution -``` - -Schedule this tool for background execution via docket. - -**Args:** -- `docket`: The Docket instance -- `arguments`: Tool arguments -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - - -#### `from_tool` - -```python -from_tool(cls, tool: Tool | Callable[..., Any]) -> TransformedTool -``` - -#### `get_span_attributes` - -```python -get_span_attributes(self) -> dict[str, Any] -``` diff --git a/docs/python-sdk/fastmcp-tools-function_parsing.mdx b/docs/python-sdk/fastmcp-tools-function_parsing.mdx deleted file mode 100644 index 2b453173f..000000000 --- a/docs/python-sdk/fastmcp-tools-function_parsing.mdx +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: function_parsing -sidebarTitle: function_parsing ---- - -# `fastmcp.tools.function_parsing` - - -Function introspection and schema generation for FastMCP tools. - -## Classes - -### `ParsedFunction` - -**Methods:** - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any], exclude_args: list[str] | None = None, validate: bool = True, wrap_non_object_output_schema: bool = True) -> ParsedFunction -``` diff --git a/docs/python-sdk/fastmcp-tools-function_tool.mdx b/docs/python-sdk/fastmcp-tools-function_tool.mdx deleted file mode 100644 index d7194a7aa..000000000 --- a/docs/python-sdk/fastmcp-tools-function_tool.mdx +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: function_tool -sidebarTitle: function_tool ---- - -# `fastmcp.tools.function_tool` - - -Standalone @tool decorator for FastMCP. - -## Functions - -### `tool` - -```python -tool(name_or_fn: str | Callable[..., Any] | None = None) -> Any -``` - - -Standalone decorator to mark a function as an MCP tool. - -Returns the original function with metadata attached. Register with a server -using mcp.add_tool(). - -**Args:** -- `run_in_thread`: Applies to sync tool functions only. When True (default), -the sync function is dispatched to a worker thread so it does not -block the event loop. Set to False to run the function inline on the -event loop thread — useful for libraries with thread affinity -(e.g. Windows COM via `uiautomation`/`comtypes`/`pywin32`, `tkinter`, -some GPU/driver bindings). Ignored for async functions. Cannot be -combined with `timeout` on a sync function\: inline calls have no -cancellation checkpoints, so the timeout would be a silent no-op. - - -## Classes - -### `DecoratedTool` - - -Protocol for functions decorated with @tool. - - -### `ToolMeta` - - -Metadata attached to functions by the @tool decorator. - - -### `FunctionTool` - -**Methods:** - -#### `from_function` - -```python -from_function(cls, fn: Callable[..., Any]) -> FunctionTool -``` - -Create a FunctionTool from a function. - -**Args:** -- `fn`: The function to wrap -- `metadata`: ToolMeta object with all configuration. If provided, -individual parameters must not be passed. -- `name, title, etc.`: Individual parameters for backwards compatibility. -Cannot be used together with metadata parameter. - - -#### `run` - -```python -run(self, arguments: dict[str, Any]) -> ToolResult -``` - -Run the tool with arguments. - - -#### `register_with_docket` - -```python -register_with_docket(self, docket: Docket) -> None -``` - -Register this tool with docket for background execution. - -Registers the raw function so Docket sees and resolves ALL -dependencies — both FastMCP's (CurrentContext, Progress) and -Docket-native ones (Retry, Timeout, ConcurrencyLimit). - - -#### `add_to_docket` - -```python -add_to_docket(self, docket: Docket, arguments: dict[str, Any], **kwargs: Any) -> Execution -``` - -Schedule this tool for background execution via docket. - -FunctionTool splats the arguments dict since .fn expects **kwargs. - -**Args:** -- `docket`: The Docket instance -- `arguments`: Tool arguments -- `fn_key`: Function lookup key in Docket registry (defaults to self.key) -- `task_key`: Redis storage key for the result -- `**kwargs`: Additional kwargs passed to docket.add() - diff --git a/docs/python-sdk/fastmcp-tools-tool_transform.mdx b/docs/python-sdk/fastmcp-tools-tool_transform.mdx deleted file mode 100644 index 9ba17c0e6..000000000 --- a/docs/python-sdk/fastmcp-tools-tool_transform.mdx +++ /dev/null @@ -1,308 +0,0 @@ ---- -title: tool_transform -sidebarTitle: tool_transform ---- - -# `fastmcp.tools.tool_transform` - -## Functions - -### `forward` - -```python -forward(**kwargs: Any) -> ToolResult -``` - - -Forward to parent tool with argument transformation applied. - -This function can only be called from within a transformed tool's custom -function. It applies argument transformation (renaming, validation) before -calling the parent tool. - -For example, if the parent tool has args `x` and `y`, but the transformed -tool has args `a` and `b`, and an `transform_args` was provided that maps `x` to -`a` and `y` to `b`, then `forward(a=1, b=2)` will call the parent tool with -`x=1` and `y=2`. - -**Args:** -- `**kwargs`: Arguments to forward to the parent tool (using transformed names). - -**Returns:** -- The ToolResult from the parent tool execution. - -**Raises:** -- `RuntimeError`: If called outside a transformed tool context. -- `TypeError`: If provided arguments don't match the transformed schema. - - -### `forward_raw` - -```python -forward_raw(**kwargs: Any) -> ToolResult -``` - - -Forward directly to parent tool without transformation. - -This function bypasses all argument transformation and validation, calling the parent -tool directly with the provided arguments. Use this when you need to call the parent -with its original parameter names and structure. - -For example, if the parent tool has args `x` and `y`, then `forward_raw(x=1, -y=2)` will call the parent tool with `x=1` and `y=2`. - -**Args:** -- `**kwargs`: Arguments to pass directly to the parent tool (using original names). - -**Returns:** -- The ToolResult from the parent tool execution. - -**Raises:** -- `RuntimeError`: If called outside a transformed tool context. - - -### `apply_transformations_to_tools` - -```python -apply_transformations_to_tools(tools: dict[str, Tool], transformations: dict[str, ToolTransformConfig]) -> dict[str, Tool] -``` - - -Apply a list of transformations to a list of tools. Tools that do not have any transformations -are left unchanged. - -Note: tools dict is keyed by prefixed key (e.g., "tool:my_tool"), -but transformations are keyed by tool name (e.g., "my_tool"). - - -## Classes - -### `ArgTransform` - - -Configuration for transforming a parent tool's argument. - -This class allows fine-grained control over how individual arguments are transformed -when creating a new tool from an existing one. You can rename arguments, change their -descriptions, add default values, or hide them from clients while passing constants. - -**Attributes:** -- `name`: New name for the argument. Use None to keep original name, or ... for no change. -- `description`: New description for the argument. Use None to remove description, or ... for no change. -- `default`: New default value for the argument. Use ... for no change. -- `default_factory`: Callable that returns a default value. Cannot be used with default. -- `type`: New type for the argument. Use ... for no change. -- `hide`: If True, hide this argument from clients but pass a constant value to parent. -- `required`: If True, make argument required (remove default). Use ... for no change. -- `examples`: Examples for the argument. Use ... for no change. - -**Examples:** - -Rename argument 'old_name' to 'new_name' -```python -ArgTransform(name="new_name") -``` - -Change description only -```python -ArgTransform(description="Updated description") -``` - -Add a default value (makes argument optional) -```python -ArgTransform(default=42) -``` - -Add a default factory (makes argument optional) -```python -ArgTransform(default_factory=lambda: time.time()) -``` - -Change the type -```python -ArgTransform(type=str) -``` - -Hide the argument entirely from clients -```python -ArgTransform(hide=True) -``` - -Hide argument but pass a constant value to parent -```python -ArgTransform(hide=True, default="constant_value") -``` - -Hide argument but pass a factory-generated value to parent -```python -ArgTransform(hide=True, default_factory=lambda: uuid.uuid4().hex) -``` - -Make an optional parameter required (removes any default) -```python -ArgTransform(required=True) -``` - -Combine multiple transformations -```python -ArgTransform(name="new_name", description="New desc", default=None, type=int) -``` - - -### `ArgTransformConfig` - - -A model for requesting a single argument transform. - - -**Methods:** - -#### `to_arg_transform` - -```python -to_arg_transform(self) -> ArgTransform -``` - -Convert the argument transform to a FastMCP argument transform. - - -### `TransformedTool` - - -A tool that is transformed from another tool. - -This class represents a tool that has been created by transforming another tool. -It supports argument renaming, schema modification, custom function injection, -structured output control, and provides context for the forward() and forward_raw() functions. - -The transformation can be purely schema-based (argument renaming, dropping, etc.) -or can include a custom function that uses forward() to call the parent tool -with transformed arguments. Output schemas and structured outputs are automatically -inherited from the parent tool but can be overridden or disabled. - -**Attributes:** -- `parent_tool`: The original tool that this tool was transformed from. -- `fn`: The function to execute when this tool is called (either the forwarding -function for pure transformations or a custom user function). -- `forwarding_fn`: Internal function that handles argument transformation and -validation when forward() is called from custom functions. - - -**Methods:** - -#### `run` - -```python -run(self, arguments: dict[str, Any]) -> ToolResult -``` - -Run the tool with context set for forward() functions. - -This method executes the tool's function while setting up the context -that allows forward() and forward_raw() to work correctly within custom -functions. - -**Args:** -- `arguments`: Dictionary of arguments to pass to the tool's function. - -**Returns:** -- ToolResult object containing content and optional structured output. - - -#### `from_tool` - -```python -from_tool(cls, tool: Tool | Callable[..., Any], name: str | None = None, version: str | NotSetT | None = NotSet, title: str | NotSetT | None = NotSet, description: str | NotSetT | None = NotSet, tags: set[str] | None = None, transform_fn: Callable[..., Any] | None = None, transform_args: dict[str, ArgTransform] | None = None, annotations: ToolAnnotations | NotSetT | None = NotSet, output_schema: dict[str, Any] | NotSetT | None = NotSet, serializer: Callable[[Any], str] | NotSetT | None = NotSet, meta: dict[str, Any] | NotSetT | None = NotSet) -> TransformedTool -``` - -Create a transformed tool from a parent tool. - -**Args:** -- `tool`: The parent tool to transform. -- `transform_fn`: Optional custom function. Can use forward() and forward_raw() -to call the parent tool. Functions with **kwargs receive transformed -argument names. -- `name`: New name for the tool. Defaults to parent tool's name. -- `version`: New version for the tool. Defaults to parent tool's version. -- `title`: New title for the tool. Defaults to parent tool's title. -- `transform_args`: Optional transformations for parent tool arguments. -Only specified arguments are transformed, others pass through unchanged. -Use ArgTransform for rename, description, default, or hide operations. -- `description`: New description. Defaults to parent's description. -- `tags`: New tags. Defaults to parent's tags. -- `annotations`: New annotations. Defaults to parent's annotations. -- `output_schema`: Control output schema for structured outputs\: -- None (default)\: Inherit from transform_fn if available, then parent tool -- dict\: Use custom output schema -- `serializer`: Deprecated. Return ToolResult from your tools for full control over serialization. -- `meta`: Control meta information\: -- NotSet (default)\: Inherit from parent tool -- dict\: Use custom meta information -- None\: Remove meta information - -**Returns:** -- TransformedTool with the specified transformations. - -**Examples:** - -# Transform specific arguments only -```python -Tool.from_tool(parent, transform_args={"old": "new"}) # Others unchanged -``` - -# Custom function with partial transforms -```python -async def custom(x: int, y: int) -> str: - result = await forward(x=x, y=y) - return f"Custom: {result}" - -Tool.from_tool(parent, transform_fn=custom, transform_args={"a": "x", "b": "y"}) -``` - -# Using **kwargs (gets all args, transformed and untransformed) -```python -async def flexible(**kwargs) -> str: - result = await forward(**kwargs) - return f"Got: {kwargs}" - -Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"}) -``` - -# Control structured outputs and schemas -```python -# Custom output schema -Tool.from_tool(parent, output_schema={ - "type": "object", - "properties": {"status": {"type": "string"}} -}) - -# Disable structured outputs -Tool.from_tool(parent, output_schema=None) - -# Return ToolResult for full control -async def custom_output(**kwargs) -> ToolResult: - result = await forward(**kwargs) - return ToolResult( - content=[TextContent(text="Summary")], - structured_content={"processed": True} - ) -``` - - -### `ToolTransformConfig` - - -Provides a way to transform a tool. - - -**Methods:** - -#### `apply` - -```python -apply(self, tool: Tool) -> TransformedTool -``` - -Create a TransformedTool from a provided tool and this transformation configuration. - diff --git a/docs/python-sdk/fastmcp-tools-__init__.mdx b/docs/python-sdk/fastmcp-tools.mdx similarity index 72% rename from docs/python-sdk/fastmcp-tools-__init__.mdx rename to docs/python-sdk/fastmcp-tools.mdx index 5b7c8b04d..f6b72c841 100644 --- a/docs/python-sdk/fastmcp-tools-__init__.mdx +++ b/docs/python-sdk/fastmcp-tools.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: tools +sidebarTitle: tools --- # `fastmcp.tools` diff --git a/docs/python-sdk/fastmcp-utilities-async_utils.mdx b/docs/python-sdk/fastmcp-utilities-async_utils.mdx index d91c4e9ba..361400e1c 100644 --- a/docs/python-sdk/fastmcp-utilities-async_utils.mdx +++ b/docs/python-sdk/fastmcp-utilities-async_utils.mdx @@ -10,7 +10,7 @@ Async utilities for FastMCP. ## Functions -### `is_coroutine_function` +### `is_coroutine_function` ```python is_coroutine_function(fn: Any) -> bool @@ -24,7 +24,7 @@ Check if a callable is a coroutine function, unwrapping functools.partial. This helper unwraps any layers of ``partial`` before checking. -### `call_sync_fn_in_threadpool` +### `call_sync_fn_in_threadpool` ```python call_sync_fn_in_threadpool(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any @@ -37,7 +37,7 @@ Uses anyio.to_thread.run_sync which properly propagates contextvars, making this safe for functions that depend on context (like dependency injection). -### `gather` +### `gather` ```python gather(*awaitables: Awaitable[T]) -> list[T] | list[T | BaseException] diff --git a/docs/python-sdk/fastmcp-utilities-auth.mdx b/docs/python-sdk/fastmcp-utilities-auth.mdx index c2d23b9a5..fbd14b943 100644 --- a/docs/python-sdk/fastmcp-utilities-auth.mdx +++ b/docs/python-sdk/fastmcp-utilities-auth.mdx @@ -10,7 +10,7 @@ Authentication utility helpers. ## Functions -### `decode_jwt_header` +### `decode_jwt_header` ```python decode_jwt_header(token: str) -> dict[str, Any] @@ -31,7 +31,7 @@ Useful for extracting the key ID (kid) for JWKS lookup. - `ValueError`: If token is not a valid JWT format -### `decode_jwt_payload` +### `decode_jwt_payload` ```python decode_jwt_payload(token: str) -> dict[str, Any] @@ -52,7 +52,7 @@ Use only for tokens received directly from trusted sources (e.g., IdP token endp - `ValueError`: If token is not a valid JWT format -### `parse_scopes` +### `parse_scopes` ```python parse_scopes(value: Any) -> list[str] | None diff --git a/docs/python-sdk/fastmcp-utilities-cli.mdx b/docs/python-sdk/fastmcp-utilities-cli.mdx index 52f2addff..6b5e73295 100644 --- a/docs/python-sdk/fastmcp-utilities-cli.mdx +++ b/docs/python-sdk/fastmcp-utilities-cli.mdx @@ -7,7 +7,7 @@ sidebarTitle: cli ## Functions -### `is_already_in_uv_subprocess` +### `is_already_in_uv_subprocess` ```python is_already_in_uv_subprocess() -> bool @@ -17,7 +17,7 @@ is_already_in_uv_subprocess() -> bool Check if we're already running in a FastMCP uv subprocess. -### `load_and_merge_config` +### `load_and_merge_config` ```python load_and_merge_config(server_spec: str | None, **cli_overrides) -> tuple[MCPServerConfig, str] @@ -37,7 +37,7 @@ run, inspect, and dev commands. - Tuple of (MCPServerConfig, resolved_server_spec) -### `log_server_banner` +### `log_server_banner` ```python log_server_banner(server: FastMCP[Any]) -> None diff --git a/docs/python-sdk/fastmcp-utilities-components.mdx b/docs/python-sdk/fastmcp-utilities-components.mdx index ab05e9d29..93bf77f0d 100644 --- a/docs/python-sdk/fastmcp-utilities-components.mdx +++ b/docs/python-sdk/fastmcp-utilities-components.mdx @@ -7,7 +7,7 @@ sidebarTitle: components ## Functions -### `get_fastmcp_metadata` +### `get_fastmcp_metadata` ```python get_fastmcp_metadata(meta: dict[str, Any] | None) -> FastMCPMeta @@ -22,9 +22,9 @@ namespace for compatibility with older FastMCP servers. ## Classes -### `FastMCPMeta` +### `FastMCPMeta` -### `FastMCPComponent` +### `FastMCPComponent` Base class for FastMCP tools, prompts, resources, and resource templates. @@ -32,7 +32,7 @@ Base class for FastMCP tools, prompts, resources, and resource templates. **Methods:** -#### `make_key` +#### `make_key` ```python make_key(cls, identifier: str) -> str @@ -47,7 +47,7 @@ Construct the lookup key for this component type. - A prefixed key like "tool:name" or "resource:uri" -#### `key` +#### `key` ```python key(self) -> str @@ -72,7 +72,7 @@ cross-type identifiers (e.g. a tool and a resource both named "foo") can't clash. -#### `get_meta` +#### `get_meta` ```python get_meta(self) -> dict[str, Any] @@ -87,7 +87,7 @@ Returns a dict that always includes a `fastmcp` key containing: Internal keys (prefixed with `_`) are stripped from the fastmcp namespace. -#### `enable` +#### `enable` ```python enable(self) -> None @@ -96,7 +96,7 @@ enable(self) -> None Removed in 3.0. Use server.enable(keys=[...]) instead. -#### `disable` +#### `disable` ```python disable(self) -> None @@ -105,7 +105,7 @@ disable(self) -> None Removed in 3.0. Use server.disable(keys=[...]) instead. -#### `copy` +#### `copy` ```python copy(self) -> Self @@ -114,7 +114,7 @@ copy(self) -> Self Create a copy of the component. -#### `register_with_docket` +#### `register_with_docket` ```python register_with_docket(self, docket: Docket) -> None @@ -126,7 +126,7 @@ No-ops if task_config.mode is "forbidden". Subclasses override to register their callable (self.run, self.read, self.render, or self.fn). -#### `add_to_docket` +#### `add_to_docket` ```python add_to_docket(self, docket: Docket, *args: Any, **kwargs: Any) -> Execution @@ -143,7 +143,7 @@ Subclasses override this to handle their specific calling conventions: The **kwargs are passed through to docket.add() (e.g., key=task_key). -#### `get_span_attributes` +#### `get_span_attributes` ```python get_span_attributes(self) -> dict[str, Any] diff --git a/docs/python-sdk/fastmcp-utilities-docstring_parsing.mdx b/docs/python-sdk/fastmcp-utilities-docstring_parsing.mdx index c3fff9eea..b8cacc823 100644 --- a/docs/python-sdk/fastmcp-utilities-docstring_parsing.mdx +++ b/docs/python-sdk/fastmcp-utilities-docstring_parsing.mdx @@ -16,7 +16,7 @@ callers. ## Functions -### `parse_docstring` +### `parse_docstring` ```python parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring @@ -32,7 +32,7 @@ docstring as the description with no parameter descriptions. ## Classes -### `ParsedDocstring` +### `ParsedDocstring` The extracted description and per-parameter descriptions from a docstring. diff --git a/docs/python-sdk/fastmcp-utilities-exceptions.mdx b/docs/python-sdk/fastmcp-utilities-exceptions.mdx index 5794f185e..563c9a176 100644 --- a/docs/python-sdk/fastmcp-utilities-exceptions.mdx +++ b/docs/python-sdk/fastmcp-utilities-exceptions.mdx @@ -7,13 +7,13 @@ sidebarTitle: exceptions ## Functions -### `iter_exc` +### `iter_exc` ```python iter_exc(group: BaseExceptionGroup) ``` -### `get_catch_handlers` +### `get_catch_handlers` ```python get_catch_handlers() -> Mapping[type[BaseException] | Iterable[type[BaseException]], Callable[[BaseExceptionGroup[Any]], Any]] diff --git a/docs/python-sdk/fastmcp-utilities-http.mdx b/docs/python-sdk/fastmcp-utilities-http.mdx index d274477c5..ae9685aaf 100644 --- a/docs/python-sdk/fastmcp-utilities-http.mdx +++ b/docs/python-sdk/fastmcp-utilities-http.mdx @@ -7,7 +7,7 @@ sidebarTitle: http ## Functions -### `find_available_port` +### `find_available_port` ```python find_available_port() -> int diff --git a/docs/python-sdk/fastmcp-utilities-inspect.mdx b/docs/python-sdk/fastmcp-utilities-inspect.mdx index a813eb51e..578a936b1 100644 --- a/docs/python-sdk/fastmcp-utilities-inspect.mdx +++ b/docs/python-sdk/fastmcp-utilities-inspect.mdx @@ -10,7 +10,7 @@ Utilities for inspecting FastMCP instances. ## Functions -### `inspect_fastmcp_v2` +### `inspect_fastmcp_v2` ```python inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo @@ -26,7 +26,7 @@ Extract information from a FastMCP v2.x instance. - FastMCPInfo dataclass containing the extracted information -### `inspect_fastmcp_v1` +### `inspect_fastmcp_v1` ```python inspect_fastmcp_v1(mcp: FastMCP1x) -> FastMCPInfo @@ -42,7 +42,7 @@ Extract information from a FastMCP v1.x instance using a Client. - FastMCPInfo dataclass containing the extracted information -### `inspect_fastmcp` +### `inspect_fastmcp` ```python inspect_fastmcp(mcp: FastMCP[Any] | FastMCP1x) -> FastMCPInfo @@ -61,7 +61,7 @@ and uses the appropriate extraction method. - FastMCPInfo dataclass containing the extracted information -### `format_fastmcp_info` +### `format_fastmcp_info` ```python format_fastmcp_info(info: FastMCPInfo) -> bytes @@ -73,7 +73,7 @@ Format FastMCPInfo as FastMCP-specific JSON. This includes FastMCP-specific fields like tags, enabled, annotations, etc. -### `format_mcp_info` +### `format_mcp_info` ```python format_mcp_info(mcp: FastMCP[Any] | FastMCP1x) -> bytes @@ -86,7 +86,7 @@ Uses Client to get the standard MCP protocol format with camelCase fields. Includes version metadata at the top level. -### `format_info` +### `format_info` ```python format_info(mcp: FastMCP[Any] | FastMCP1x, format: InspectFormat | Literal['fastmcp', 'mcp'], info: FastMCPInfo | None = None) -> bytes @@ -106,37 +106,37 @@ Format server information according to the specified format. ## Classes -### `ToolInfo` +### `ToolInfo` Information about a tool. -### `PromptInfo` +### `PromptInfo` Information about a prompt. -### `ResourceInfo` +### `ResourceInfo` Information about a resource. -### `TemplateInfo` +### `TemplateInfo` Information about a resource template. -### `FastMCPInfo` +### `FastMCPInfo` Information extracted from a FastMCP instance. -### `InspectFormat` +### `InspectFormat` Output format for inspect command. diff --git a/docs/python-sdk/fastmcp-utilities-json_schema.mdx b/docs/python-sdk/fastmcp-utilities-json_schema.mdx index 4372c9ab9..53655abd4 100644 --- a/docs/python-sdk/fastmcp-utilities-json_schema.mdx +++ b/docs/python-sdk/fastmcp-utilities-json_schema.mdx @@ -7,7 +7,7 @@ sidebarTitle: json_schema ## Functions -### `dereference_refs` +### `dereference_refs` ```python dereference_refs(schema: dict[str, Any]) -> dict[str, Any] @@ -40,7 +40,7 @@ schemas from untrusted servers. - when no longer needed -### `resolve_root_ref` +### `resolve_root_ref` ```python resolve_root_ref(schema: dict[str, Any]) -> dict[str, Any] @@ -62,7 +62,7 @@ the referenced definition while preserving $defs for nested references. - if no resolution is needed -### `compress_schema` +### `compress_schema` ```python compress_schema(schema: dict[str, Any], prune_params: list[str] | None = None, prune_additional_properties: bool = False, prune_titles: bool = False, dereference: bool = False) -> dict[str, Any] diff --git a/docs/python-sdk/fastmcp-utilities-json_schema_type.mdx b/docs/python-sdk/fastmcp-utilities-json_schema_type.mdx index d505b28b7..cd4634901 100644 --- a/docs/python-sdk/fastmcp-utilities-json_schema_type.mdx +++ b/docs/python-sdk/fastmcp-utilities-json_schema_type.mdx @@ -60,7 +60,7 @@ Example: ## Functions -### `json_schema_to_type` +### `json_schema_to_type` ```python json_schema_to_type(schema: Mapping[str, Any] | bool, name: str | None = None) -> type @@ -126,4 +126,4 @@ class Name: ## Classes -### `JSONSchema` +### `JSONSchema` diff --git a/docs/python-sdk/fastmcp-utilities-lifespan.mdx b/docs/python-sdk/fastmcp-utilities-lifespan.mdx index 912cbfad6..f4dcee33a 100644 --- a/docs/python-sdk/fastmcp-utilities-lifespan.mdx +++ b/docs/python-sdk/fastmcp-utilities-lifespan.mdx @@ -10,7 +10,7 @@ Lifespan utilities for combining async context manager lifespans. ## Functions -### `combine_lifespans` +### `combine_lifespans` ```python combine_lifespans(*lifespans: Callable[[AppT], AbstractAsyncContextManager[Mapping[str, Any] | None]]) -> Callable[[AppT], AbstractAsyncContextManager[dict[str, Any]]] diff --git a/docs/python-sdk/fastmcp-utilities-logging.mdx b/docs/python-sdk/fastmcp-utilities-logging.mdx index 2b5fea4ae..f3b58bf7e 100644 --- a/docs/python-sdk/fastmcp-utilities-logging.mdx +++ b/docs/python-sdk/fastmcp-utilities-logging.mdx @@ -10,7 +10,7 @@ Logging utilities for FastMCP. ## Functions -### `get_logger` +### `get_logger` ```python get_logger(name: str) -> logging.Logger @@ -26,7 +26,7 @@ Get a logger nested under FastMCP namespace. - a configured logger instance -### `configure_logging` +### `configure_logging` ```python configure_logging(level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | int = 'INFO', logger: logging.Logger | None = None, enable_rich_tracebacks: bool | None = None, **rich_kwargs: Any) -> None @@ -41,7 +41,7 @@ Configure logging for FastMCP. - `rich_kwargs`: the parameters to use for creating RichHandler -### `temporary_log_level` +### `temporary_log_level` ```python temporary_log_level(level: str | None, logger: logging.Logger | None = None, enable_rich_tracebacks: bool | None = None, **rich_kwargs: Any) diff --git a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-base.mdx b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-base.mdx index f59bb18b1..f8e764a22 100644 --- a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-base.mdx +++ b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-base.mdx @@ -7,7 +7,7 @@ sidebarTitle: base ## Classes -### `Environment` +### `Environment` Base class for environment configuration. @@ -15,7 +15,7 @@ Base class for environment configuration. **Methods:** -#### `build_command` +#### `build_command` ```python build_command(self, command: list[str]) -> list[str] @@ -30,7 +30,7 @@ Build the full command with environment setup. - Full command ready for subprocess execution -#### `prepare` +#### `prepare` ```python prepare(self, output_dir: Path | None = None) -> None diff --git a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-uv.mdx b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-uv.mdx index e5a2d6a11..8e9e5b2db 100644 --- a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-uv.mdx +++ b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-environments-uv.mdx @@ -7,7 +7,7 @@ sidebarTitle: uv ## Classes -### `UVEnvironment` +### `UVEnvironment` Configuration for Python environment setup. @@ -15,7 +15,7 @@ Configuration for Python environment setup. **Methods:** -#### `build_command` +#### `build_command` ```python build_command(self, command: list[str]) -> list[str] @@ -31,7 +31,7 @@ Build complete uv run command with environment args and command to execute. - If no environment configuration is set, returns the command unchanged. -#### `prepare` +#### `prepare` ```python prepare(self, output_dir: Path | None = None) -> None diff --git a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-mcp_server_config.mdx b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-mcp_server_config.mdx index 460f1f83d..dc0dd1276 100644 --- a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-mcp_server_config.mdx +++ b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-mcp_server_config.mdx @@ -15,7 +15,7 @@ command-line arguments. ## Functions -### `generate_schema` +### `generate_schema` ```python generate_schema(output_path: Path | str | None = None) -> dict[str, Any] | None @@ -38,7 +38,7 @@ validation and auto-completion. ## Classes -### `Deployment` +### `Deployment` Configuration for server deployment and runtime settings. @@ -46,7 +46,7 @@ Configuration for server deployment and runtime settings. **Methods:** -#### `apply_runtime_settings` +#### `apply_runtime_settings` ```python apply_runtime_settings(self, config_path: Path | None = None) -> None @@ -62,7 +62,7 @@ For example: "API_URL": "https://api.${ENVIRONMENT}.example.com" will substitute the value of the ENVIRONMENT variable at runtime. -### `MCPServerConfig` +### `MCPServerConfig` Configuration for a FastMCP server. @@ -73,7 +73,7 @@ a FastMCP server in a declarative format. **Methods:** -#### `validate_source` +#### `validate_source` ```python validate_source(cls, v: dict | Source) -> SourceType @@ -89,7 +89,7 @@ No string parsing happens here - that's only at CLI boundaries. MCPServerConfig works only with properly typed objects. -#### `validate_environment` +#### `validate_environment` ```python validate_environment(cls, v: dict | Any) -> EnvironmentType @@ -100,7 +100,7 @@ Ensure environment has a type field for discrimination. For backward compatibility, if no type is specified, default to "uv". -#### `validate_deployment` +#### `validate_deployment` ```python validate_deployment(cls, v: dict | Deployment) -> Deployment @@ -113,7 +113,7 @@ Accepts: - dict that can be converted to Deployment -#### `from_file` +#### `from_file` ```python from_file(cls, file_path: Path) -> MCPServerConfig @@ -133,7 +133,7 @@ Load configuration from a JSON file. - `pydantic.ValidationError`: If the configuration is invalid -#### `from_cli_args` +#### `from_cli_args` ```python from_cli_args(cls, source: FileSystemSource, transport: Literal['stdio', 'http', 'sse', 'streamable-http'] | None = None, host: str | None = None, port: int | None = None, path: str | None = None, log_level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | None = None, python: str | None = None, dependencies: list[str] | None = None, requirements: str | None = None, project: str | None = None, editable: str | None = None, env: dict[str, str] | None = None, cwd: str | None = None, args: list[str] | None = None) -> MCPServerConfig @@ -164,7 +164,7 @@ goes through a config object. - MCPServerConfig instance -#### `find_config` +#### `find_config` ```python find_config(cls, start_path: Path | None = None) -> Path | None @@ -179,7 +179,7 @@ Find a fastmcp.json file in the specified directory. - Path to the configuration file, or None if not found -#### `prepare` +#### `prepare` ```python prepare(self, skip_source: bool = False, output_dir: Path | None = None) -> None @@ -195,7 +195,7 @@ When output_dir is None, does ephemeral caching (for backwards compatibility). - `output_dir`: Directory to create the persistent uv project in (optional) -#### `prepare_environment` +#### `prepare_environment` ```python prepare_environment(self, output_dir: Path | None = None) -> None @@ -210,7 +210,7 @@ Prepare the Python environment. Delegates to the environment's prepare() method -#### `prepare_source` +#### `prepare_source` ```python prepare_source(self) -> None @@ -221,7 +221,7 @@ Prepare the source for loading. Delegates to the source's prepare() method. -#### `run_server` +#### `run_server` ```python run_server(self, **kwargs: Any) -> None diff --git a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-base.mdx b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-base.mdx index 764454b6d..4c5793007 100644 --- a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-base.mdx +++ b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-base.mdx @@ -7,7 +7,7 @@ sidebarTitle: base ## Classes -### `Source` +### `Source` Abstract base class for all source types. @@ -15,7 +15,7 @@ Abstract base class for all source types. **Methods:** -#### `prepare` +#### `prepare` ```python prepare(self) -> None @@ -28,7 +28,7 @@ this method performs that preparation. For sources that don't need preparation (e.g., local files), this is a no-op. -#### `load_server` +#### `load_server` ```python load_server(self) -> Any diff --git a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-filesystem.mdx b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-filesystem.mdx index 15bd86966..2abce7f16 100644 --- a/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-filesystem.mdx +++ b/docs/python-sdk/fastmcp-utilities-mcp_server_config-v1-sources-filesystem.mdx @@ -7,7 +7,7 @@ sidebarTitle: filesystem ## Classes -### `FileSystemSource` +### `FileSystemSource` Source for local Python files. @@ -15,7 +15,7 @@ Source for local Python files. **Methods:** -#### `parse_path_with_object` +#### `parse_path_with_object` ```python parse_path_with_object(cls, v: str) -> str @@ -27,7 +27,7 @@ This validator runs before the model is created, allowing us to handle the "file.py:object" syntax at the model boundary. -#### `load_server` +#### `load_server` ```python load_server(self) -> Any diff --git a/docs/python-sdk/fastmcp-utilities-mime.mdx b/docs/python-sdk/fastmcp-utilities-mime.mdx index b823d447b..99455c74a 100644 --- a/docs/python-sdk/fastmcp-utilities-mime.mdx +++ b/docs/python-sdk/fastmcp-utilities-mime.mdx @@ -14,7 +14,7 @@ so it can be safely imported from anywhere. ## Functions -### `resolve_ui_mime_type` +### `resolve_ui_mime_type` ```python resolve_ui_mime_type(uri: str, explicit_mime_type: str | None) -> str | None diff --git a/docs/python-sdk/fastmcp-utilities-openapi-director.mdx b/docs/python-sdk/fastmcp-utilities-openapi-director.mdx deleted file mode 100644 index 8fc5e2216..000000000 --- a/docs/python-sdk/fastmcp-utilities-openapi-director.mdx +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: director -sidebarTitle: director ---- - -# `fastmcp.utilities.openapi.director` - - -Request director using openapi-core for stateless HTTP request building. - -## Classes - -### `RequestDirector` - - -Builds httpx.Request objects from HTTPRoute and arguments using openapi-core. - - -**Methods:** - -#### `build` - -```python -build(self, route: HTTPRoute, flat_args: dict[str, Any], base_url: str = 'http://localhost') -> httpx.Request -``` - -Constructs a final httpx.Request object, handling all OpenAPI serialization. - -**Args:** -- `route`: HTTPRoute containing OpenAPI operation details -- `flat_args`: Flattened arguments from LLM (may include suffixed parameters) -- `base_url`: Base URL for the request - -**Returns:** -- httpx.Request: Properly formatted HTTP request - diff --git a/docs/python-sdk/fastmcp-utilities-openapi-formatters.mdx b/docs/python-sdk/fastmcp-utilities-openapi-formatters.mdx deleted file mode 100644 index 4d5ad3a90..000000000 --- a/docs/python-sdk/fastmcp-utilities-openapi-formatters.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: formatters -sidebarTitle: formatters ---- - -# `fastmcp.utilities.openapi.formatters` - - -Parameter formatting functions for OpenAPI operations. - -## Functions - -### `format_array_parameter` - -```python -format_array_parameter(values: list, parameter_name: str, is_query_parameter: bool = False) -> str | list -``` - - -Format an array parameter according to OpenAPI specifications. - -**Args:** -- `values`: List of values to format -- `parameter_name`: Name of the parameter (for error messages) -- `is_query_parameter`: If True, can return list for explode=True behavior - -**Returns:** -- String (comma-separated) or list (for query params with explode=True) - - -### `format_deep_object_parameter` - -```python -format_deep_object_parameter(param_value: dict, parameter_name: str) -> dict[str, str] -``` - - -Format a dictionary parameter for deep-object style serialization. - -According to OpenAPI 3.0 spec, deepObject style with explode=true serializes -object properties as separate query parameters with bracket notation. - -For example, `{"id": "123", "type": "user"}` becomes -`param[id]=123¶m[type]=user`. - -**Args:** -- `param_value`: Dictionary value to format -- `parameter_name`: Name of the parameter - -**Returns:** -- Dictionary with bracketed parameter names as keys - - -### `generate_example_from_schema` - -```python -generate_example_from_schema(schema: JsonSchema | None) -> Any -``` - - -Generate a simple example value from a JSON schema dictionary. -Very basic implementation focusing on types. - - -### `format_json_for_description` - -```python -format_json_for_description(data: Any, indent: int = 2) -> str -``` - - -Formats Python data as a JSON string block for Markdown. - - -### `format_description_with_responses` - -```python -format_description_with_responses(base_description: str, responses: dict[str, Any], parameters: list[ParameterInfo] | None = None, request_body: RequestBodyInfo | None = None) -> str -``` - - -Formats the base description string with response, parameter, and request body information. - -**Args:** -- `base_description`: The initial description to be formatted. -- `responses`: A dictionary of response information, keyed by status code. -- `parameters`: A list of parameter information, -including path and query parameters. Each parameter includes details such as name, -location, whether it is required, and a description. -- `request_body`: Information about the request body, -including its description, whether it is required, and its content schema. - -**Returns:** -- The formatted description string with additional details about responses, parameters, -- and the request body. - diff --git a/docs/python-sdk/fastmcp-utilities-openapi-json_schema_converter.mdx b/docs/python-sdk/fastmcp-utilities-openapi-json_schema_converter.mdx deleted file mode 100644 index ad596a5c9..000000000 --- a/docs/python-sdk/fastmcp-utilities-openapi-json_schema_converter.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: json_schema_converter -sidebarTitle: json_schema_converter ---- - -# `fastmcp.utilities.openapi.json_schema_converter` - - - -Clean OpenAPI 3.0 to JSON Schema converter for the experimental parser. - -This module provides a systematic approach to converting OpenAPI 3.0 schemas -to JSON Schema, inspired by py-openapi-schema-to-json-schema but optimized -for our specific use case. - - -## Functions - -### `convert_openapi_schema_to_json_schema` - -```python -convert_openapi_schema_to_json_schema(schema: dict[str, Any], openapi_version: str | None = None, remove_read_only: bool = False, remove_write_only: bool = False, convert_one_of_to_any_of: bool = True) -> dict[str, Any] -``` - - -Convert an OpenAPI schema to JSON Schema format. - -This is a clean, systematic approach that: -1. Removes OpenAPI-specific fields -2. Converts nullable fields to type arrays (for OpenAPI 3.0 only) -3. Converts oneOf to anyOf for overlapping union handling -4. Recursively processes nested schemas -5. Optionally removes readOnly/writeOnly properties - -**Args:** -- `schema`: OpenAPI schema dictionary -- `openapi_version`: OpenAPI version for optimization -- `remove_read_only`: Whether to remove readOnly properties -- `remove_write_only`: Whether to remove writeOnly properties -- `convert_one_of_to_any_of`: Whether to convert oneOf to anyOf - -**Returns:** -- JSON Schema-compatible dictionary - - -### `convert_schema_definitions` - -```python -convert_schema_definitions(schema_definitions: dict[str, Any] | None, openapi_version: str | None = None, **kwargs) -> dict[str, Any] -``` - - -Convert a dictionary of OpenAPI schema definitions to JSON Schema. - -**Args:** -- `schema_definitions`: Dictionary of schema definitions -- `openapi_version`: OpenAPI version for optimization -- `**kwargs`: Additional arguments passed to convert_openapi_schema_to_json_schema - -**Returns:** -- Dictionary of converted schema definitions - diff --git a/docs/python-sdk/fastmcp-utilities-openapi-models.mdx b/docs/python-sdk/fastmcp-utilities-openapi-models.mdx deleted file mode 100644 index 02a3fbe9e..000000000 --- a/docs/python-sdk/fastmcp-utilities-openapi-models.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: models -sidebarTitle: models ---- - -# `fastmcp.utilities.openapi.models` - - -Intermediate Representation (IR) models for OpenAPI operations. - -## Classes - -### `ParameterInfo` - - -Represents a single parameter for an HTTP operation in our IR. - - -### `RequestBodyInfo` - - -Represents the request body for an HTTP operation in our IR. - - -### `ResponseInfo` - - -Represents response information in our IR. - - -### `HTTPRoute` - - -Intermediate Representation for a single OpenAPI operation. - diff --git a/docs/python-sdk/fastmcp-utilities-openapi-parser.mdx b/docs/python-sdk/fastmcp-utilities-openapi-parser.mdx deleted file mode 100644 index 0a9a2a272..000000000 --- a/docs/python-sdk/fastmcp-utilities-openapi-parser.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: parser -sidebarTitle: parser ---- - -# `fastmcp.utilities.openapi.parser` - - -OpenAPI parsing logic for converting OpenAPI specs to HTTPRoute objects. - -## Functions - -### `parse_openapi_to_http_routes` - -```python -parse_openapi_to_http_routes(openapi_dict: dict[str, Any]) -> list[HTTPRoute] -``` - - -Parses an OpenAPI schema dictionary into a list of HTTPRoute objects -using the openapi-pydantic library. - -Supports both OpenAPI 3.0.x and 3.1.x versions. - - -## Classes - -### `OpenAPIParser` - - -Unified parser for OpenAPI schemas with generic type parameters to handle both 3.0 and 3.1. - - -**Methods:** - -#### `parse` - -```python -parse(self) -> list[HTTPRoute] -``` - -Parse the OpenAPI schema into HTTP routes. - diff --git a/docs/python-sdk/fastmcp-utilities-openapi-schemas.mdx b/docs/python-sdk/fastmcp-utilities-openapi-schemas.mdx deleted file mode 100644 index 47ee1e699..000000000 --- a/docs/python-sdk/fastmcp-utilities-openapi-schemas.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: schemas -sidebarTitle: schemas ---- - -# `fastmcp.utilities.openapi.schemas` - - -Schema manipulation utilities for OpenAPI operations. - -## Functions - -### `clean_schema_for_display` - -```python -clean_schema_for_display(schema: JsonSchema | None) -> JsonSchema | None -``` - - -Clean up a schema dictionary for display by removing internal/complex fields. - - -### `extract_output_schema_from_responses` - -```python -extract_output_schema_from_responses(responses: dict[str, ResponseInfo], schema_definitions: dict[str, Any] | None = None, openapi_version: str | None = None) -> dict[str, Any] | None -``` - - -Extract output schema from OpenAPI responses for use as MCP tool output schema. - -This function finds the first successful response (200, 201, 202, 204) with a -JSON-compatible content type and extracts its schema. If the schema is not an -object type, it wraps it to comply with MCP requirements. - -**Args:** -- `responses`: Dictionary of ResponseInfo objects keyed by status code -- `schema_definitions`: Optional schema definitions to include in the output schema -- `openapi_version`: OpenAPI version string, used to optimize nullable field handling - -**Returns:** -- MCP-compliant output schema with potential wrapping, or None if no suitable schema found - diff --git a/docs/python-sdk/fastmcp-utilities-openapi-__init__.mdx b/docs/python-sdk/fastmcp-utilities-openapi.mdx similarity index 74% rename from docs/python-sdk/fastmcp-utilities-openapi-__init__.mdx rename to docs/python-sdk/fastmcp-utilities-openapi.mdx index df0331f9e..cb8bcf974 100644 --- a/docs/python-sdk/fastmcp-utilities-openapi-__init__.mdx +++ b/docs/python-sdk/fastmcp-utilities-openapi.mdx @@ -1,6 +1,6 @@ --- -title: __init__ -sidebarTitle: __init__ +title: openapi +sidebarTitle: openapi --- # `fastmcp.utilities.openapi` diff --git a/docs/python-sdk/fastmcp-utilities-pagination.mdx b/docs/python-sdk/fastmcp-utilities-pagination.mdx index 0381a36aa..7008f2355 100644 --- a/docs/python-sdk/fastmcp-utilities-pagination.mdx +++ b/docs/python-sdk/fastmcp-utilities-pagination.mdx @@ -10,7 +10,7 @@ Pagination utilities for MCP list operations. ## Functions -### `paginate_sequence` +### `paginate_sequence` ```python paginate_sequence(items: Sequence[T], cursor: str | None, page_size: int) -> tuple[list[T], str | None] @@ -33,7 +33,7 @@ Paginate a sequence of items. ## Classes -### `CursorState` +### `CursorState` Internal representation of pagination cursor state. @@ -44,7 +44,7 @@ per the MCP spec - they should not parse or modify cursors. **Methods:** -#### `encode` +#### `encode` ```python encode(self) -> str @@ -53,7 +53,7 @@ encode(self) -> str Encode cursor state to an opaque string. -#### `decode` +#### `decode` ```python decode(cls, cursor: str) -> CursorState diff --git a/docs/python-sdk/fastmcp-utilities-skills.mdx b/docs/python-sdk/fastmcp-utilities-skills.mdx index 807d07782..cdbbbad2a 100644 --- a/docs/python-sdk/fastmcp-utilities-skills.mdx +++ b/docs/python-sdk/fastmcp-utilities-skills.mdx @@ -10,7 +10,7 @@ Client utilities for discovering and downloading skills from MCP servers. ## Functions -### `list_skills` +### `list_skills` ```python list_skills(client: Client) -> list[SkillSummary] @@ -29,7 +29,7 @@ Discovers skills by finding resources with URIs matching the - List of SkillSummary objects with name, description, and URI -### `get_skill_manifest` +### `get_skill_manifest` ```python get_skill_manifest(client: Client, skill_name: str) -> SkillManifest @@ -49,7 +49,7 @@ Get the manifest for a specific skill. - `ValueError`: If manifest cannot be read or parsed -### `download_skill` +### `download_skill` ```python download_skill(client: Client, skill_name: str, target_dir: str | Path) -> Path @@ -75,7 +75,7 @@ Creates a subdirectory named after the skill containing all files. - `FileExistsError`: If skill directory exists and overwrite=False -### `sync_skills` +### `sync_skills` ```python sync_skills(client: Client, target_dir: str | Path) -> list[Path] @@ -95,19 +95,19 @@ Download all available skills from a server. ## Classes -### `SkillSummary` +### `SkillSummary` Summary information about a skill available on a server. -### `SkillFile` +### `SkillFile` Information about a file within a skill. -### `SkillManifest` +### `SkillManifest` Full manifest of a skill including all files. diff --git a/docs/python-sdk/fastmcp-utilities-tests.mdx b/docs/python-sdk/fastmcp-utilities-tests.mdx index 5a40ff61f..ca779b9a2 100644 --- a/docs/python-sdk/fastmcp-utilities-tests.mdx +++ b/docs/python-sdk/fastmcp-utilities-tests.mdx @@ -7,7 +7,7 @@ sidebarTitle: tests ## Functions -### `temporary_settings` +### `temporary_settings` ```python temporary_settings(**kwargs: Any) @@ -20,7 +20,7 @@ Temporarily override FastMCP setting values. - `**kwargs`: The settings to override, including nested settings. -### `run_server_in_process` +### `run_server_in_process` ```python run_server_in_process(server_fn: Callable[..., None], *args: Any, **kwargs: Any) -> Generator[str, None, None] @@ -43,7 +43,7 @@ not pickleable, so we need a function that creates and runs one. - The server URL. -### `run_server_async` +### `run_server_async` ```python run_server_async(server: FastMCP, port: int | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http', path: str = '/mcp', host: str = '127.0.0.1') -> AsyncGenerator[str, None] @@ -66,7 +66,7 @@ sleeps, and cleanup issues. ## Classes -### `HeadlessOAuth` +### `HeadlessOAuth` OAuth provider that bypasses browser interaction for testing. @@ -77,7 +77,7 @@ instead of opening a browser and running a callback server. Useful for automated **Methods:** -#### `redirect_handler` +#### `redirect_handler` ```python redirect_handler(self, authorization_url: str) -> None @@ -86,7 +86,7 @@ redirect_handler(self, authorization_url: str) -> None Make HTTP request to authorization URL and store response for callback handler. -#### `callback_handler` +#### `callback_handler` ```python callback_handler(self) -> tuple[str, str | None] diff --git a/docs/python-sdk/fastmcp-utilities-timeout.mdx b/docs/python-sdk/fastmcp-utilities-timeout.mdx index 3a8cb41b9..c9c890e1c 100644 --- a/docs/python-sdk/fastmcp-utilities-timeout.mdx +++ b/docs/python-sdk/fastmcp-utilities-timeout.mdx @@ -10,7 +10,7 @@ Timeout normalization utilities. ## Functions -### `normalize_timeout_to_timedelta` +### `normalize_timeout_to_timedelta` ```python normalize_timeout_to_timedelta(value: int | float | datetime.timedelta | None) -> datetime.timedelta | None @@ -26,7 +26,7 @@ Normalize a timeout value to a timedelta. - timedelta if value provided, None otherwise -### `normalize_timeout_to_seconds` +### `normalize_timeout_to_seconds` ```python normalize_timeout_to_seconds(value: int | float | datetime.timedelta | None) -> float | None diff --git a/docs/python-sdk/fastmcp-utilities-token_cache.mdx b/docs/python-sdk/fastmcp-utilities-token_cache.mdx index af0a890f8..a831d2057 100644 --- a/docs/python-sdk/fastmcp-utilities-token_cache.mdx +++ b/docs/python-sdk/fastmcp-utilities-token_cache.mdx @@ -30,7 +30,7 @@ Example: ## Classes -### `TokenCache` +### `TokenCache` TTL-based in-memory cache for ``AccessToken`` objects. @@ -50,7 +50,7 @@ when ``max_size`` is ``0``. Negative values raise ``ValueError``. **Methods:** -#### `enabled` +#### `enabled` ```python enabled(self) -> bool @@ -59,7 +59,7 @@ enabled(self) -> bool Return whether caching is active. -#### `get` +#### `get` ```python get(self, token: str) -> tuple[bool, AccessToken | None] @@ -73,7 +73,7 @@ Look up a cached verification result. - copy that is safe to mutate. -#### `set` +#### `set` ```python set(self, token: str, result: AccessToken) -> None diff --git a/docs/python-sdk/fastmcp-utilities-types.mdx b/docs/python-sdk/fastmcp-utilities-types.mdx index 562b6d961..e1379ae4b 100644 --- a/docs/python-sdk/fastmcp-utilities-types.mdx +++ b/docs/python-sdk/fastmcp-utilities-types.mdx @@ -10,13 +10,13 @@ Common types used across FastMCP. ## Functions -### `get_fn_name` +### `get_fn_name` ```python get_fn_name(fn: Callable[..., Any]) -> str ``` -### `get_cached_typeadapter` +### `get_cached_typeadapter` ```python get_cached_typeadapter(cls: T) -> TypeAdapter[T] @@ -29,7 +29,7 @@ However, this isn't feasible for user-generated functions. Instead, we use a cache to minimize the cost of creating them as much as possible. -### `issubclass_safe` +### `issubclass_safe` ```python issubclass_safe(cls: type, base: type) -> bool @@ -39,7 +39,7 @@ issubclass_safe(cls: type, base: type) -> bool Check if cls is a subclass of base, even if cls is a type variable. -### `is_class_member_of_type` +### `is_class_member_of_type` ```python is_class_member_of_type(cls: Any, base: type) -> bool @@ -52,7 +52,7 @@ Base can be a type, a UnionType, or an Annotated type. Generic types are not considered members (e.g. T is not a member of list\[T]). -### `find_kwarg_by_type` +### `find_kwarg_by_type` ```python find_kwarg_by_type(fn: Callable, kwarg_type: type) -> str | None @@ -64,7 +64,7 @@ Find the name of the kwarg that is of type kwarg_type. Includes union types that contain the kwarg_type, as well as Annotated types. -### `create_function_without_params` +### `create_function_without_params` ```python create_function_without_params(fn: Callable[..., Any], exclude_params: list[str]) -> Callable[..., Any] @@ -77,7 +77,7 @@ This is used to exclude parameters from type adapter processing when they can't The excluded parameters are removed from the function's __annotations__ dictionary. -### `replace_type` +### `replace_type` ```python replace_type(type_, type_map: dict[type, type]) @@ -106,13 +106,13 @@ list[list[str]] ## Classes -### `FastMCPBaseModel` +### `FastMCPBaseModel` Base model for FastMCP models. -### `Image` +### `Image` Helper class for returning images from tools. @@ -120,7 +120,7 @@ Helper class for returning images from tools. **Methods:** -#### `to_image_content` +#### `to_image_content` ```python to_image_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.ImageContent @@ -129,7 +129,7 @@ to_image_content(self, mime_type: str | None = None, annotations: Annotations | Convert to MCP ImageContent. -#### `to_data_uri` +#### `to_data_uri` ```python to_data_uri(self, mime_type: str | None = None) -> str @@ -138,7 +138,7 @@ to_data_uri(self, mime_type: str | None = None) -> str Get image as a data URI. -### `Audio` +### `Audio` Helper class for returning audio from tools. @@ -146,13 +146,13 @@ Helper class for returning audio from tools. **Methods:** -#### `to_audio_content` +#### `to_audio_content` ```python to_audio_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.AudioContent ``` -### `File` +### `File` Helper class for returning file data from tools. @@ -160,10 +160,10 @@ Helper class for returning file data from tools. **Methods:** -#### `to_resource_content` +#### `to_resource_content` ```python to_resource_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.EmbeddedResource ``` -### `ContextSamplingFallbackProtocol` +### `ContextSamplingFallbackProtocol` diff --git a/docs/python-sdk/fastmcp-utilities-ui.mdx b/docs/python-sdk/fastmcp-utilities-ui.mdx index eb060d2d3..7687df7ea 100644 --- a/docs/python-sdk/fastmcp-utilities-ui.mdx +++ b/docs/python-sdk/fastmcp-utilities-ui.mdx @@ -15,7 +15,7 @@ consent pages, and other user-facing interfaces. ## Functions -### `create_page` +### `create_page` ```python create_page(content: str, title: str = 'FastMCP', additional_styles: str = '', csp_policy: str = "default-src 'none'; style-src 'unsafe-inline'; img-src https: data:; base-uri 'none'") -> str @@ -35,7 +35,7 @@ If empty string "", the CSP meta tag is omitted entirely. - Complete HTML page as string -### `create_logo` +### `create_logo` ```python create_logo(icon_url: str | None = None, alt_text: str = 'FastMCP') -> str @@ -52,7 +52,7 @@ Create logo HTML. - HTML for logo image tag. -### `create_status_message` +### `create_status_message` ```python create_status_message(message: str, is_success: bool = True) -> str @@ -69,7 +69,7 @@ Create a status message with icon. - HTML for status message -### `create_info_box` +### `create_info_box` ```python create_info_box(content: str, is_error: bool = False, centered: bool = False, monospace: bool = False) -> str @@ -88,7 +88,7 @@ Create an info box. - HTML for info box -### `create_detail_box` +### `create_detail_box` ```python create_detail_box(rows: list[tuple[str, str]]) -> str @@ -104,7 +104,7 @@ Create a detail box with key-value pairs. - HTML for detail box -### `create_button_group` +### `create_button_group` ```python create_button_group(buttons: list[tuple[str, str, str]]) -> str @@ -120,7 +120,7 @@ Create a group of buttons. - HTML for button group -### `create_secure_html_response` +### `create_secure_html_response` ```python create_secure_html_response(html: str, status_code: int = 200) -> HTMLResponse diff --git a/docs/python-sdk/fastmcp-utilities-version_check.mdx b/docs/python-sdk/fastmcp-utilities-version_check.mdx index b27951eda..6a4377a08 100644 --- a/docs/python-sdk/fastmcp-utilities-version_check.mdx +++ b/docs/python-sdk/fastmcp-utilities-version_check.mdx @@ -10,7 +10,7 @@ Version checking utilities for FastMCP. ## Functions -### `get_latest_version` +### `get_latest_version` ```python get_latest_version(include_prereleases: bool = False) -> str | None @@ -26,7 +26,7 @@ Get the latest version of FastMCP from PyPI, using cache when available. - The latest version string, or None if unavailable. -### `check_for_newer_version` +### `check_for_newer_version` ```python check_for_newer_version() -> str | None diff --git a/docs/python-sdk/fastmcp-utilities-versions.mdx b/docs/python-sdk/fastmcp-utilities-versions.mdx index c571c571f..0e390aef9 100644 --- a/docs/python-sdk/fastmcp-utilities-versions.mdx +++ b/docs/python-sdk/fastmcp-utilities-versions.mdx @@ -22,7 +22,7 @@ Examples: ## Functions -### `parse_version_key` +### `parse_version_key` ```python parse_version_key(version: str | None) -> VersionKey @@ -38,7 +38,7 @@ Parse a version string into a sortable key. - A VersionKey suitable for sorting. -### `version_sort_key` +### `version_sort_key` ```python version_sort_key(component: FastMCPComponent) -> VersionKey @@ -56,7 +56,7 @@ Use with sorted() or max() to order components by version. - A sortable VersionKey. -### `compare_versions` +### `compare_versions` ```python compare_versions(a: str | None, b: str | None) -> int @@ -73,7 +73,7 @@ Compare two version strings. - -1 if a < b, 0 if a == b, 1 if a > b. -### `is_version_greater` +### `is_version_greater` ```python is_version_greater(a: str | None, b: str | None) -> bool @@ -90,7 +90,7 @@ Check if version a is greater than version b. - True if a > b, False otherwise. -### `max_version` +### `max_version` ```python max_version(a: str | None, b: str | None) -> str | None @@ -107,7 +107,7 @@ Return the greater of two versions. - The greater version, or None if both are None. -### `min_version` +### `min_version` ```python min_version(a: str | None, b: str | None) -> str | None @@ -124,7 +124,7 @@ Return the lesser of two versions. - The lesser version, or None if both are None. -### `dedupe_with_versions` +### `dedupe_with_versions` ```python dedupe_with_versions(components: Sequence[C], key_fn: Callable[[C], str]) -> list[C] @@ -146,7 +146,7 @@ and injects available versions into meta if any component is versioned. ## Classes -### `VersionSpec` +### `VersionSpec` Specification for filtering components by version. @@ -163,7 +163,7 @@ match any spec. **Methods:** -#### `matches` +#### `matches` ```python matches(self, version: str | None) -> bool @@ -182,7 +182,7 @@ from version-specific rules. - True if the version matches the spec. -#### `intersect` +#### `intersect` ```python intersect(self, other: VersionSpec | None) -> VersionSpec @@ -201,7 +201,7 @@ the intersection validates "1.0" is in range and returns the exact spec. - A VersionSpec that matches only versions satisfying both specs. -### `VersionKey` +### `VersionKey` A comparable version key that handles None, PEP 440 versions, and strings.