Python Library Documentation: class FastMCP in module mcp.server.fastmcp.server

class FFaassttMMCCPP(typing.Generic)
 |  FastMCP(
 |      name: 'str | None' = None,
 |      instructions: 'str | None' = None,
 |      website_url: 'str | None' = None,
 |      icons: 'list[Icon] | None' = None,
 |      auth_server_provider: 'OAuthAuthorizationServerProvider[Any, Any, Any] | None' = None,
 |      token_verifier: 'TokenVerifier | None' = None,
 |      event_store: 'EventStore | None' = None,
 |      retry_interval: 'int | None' = None,
 |      *,
 |      tools: 'list[Tool] | None' = None,
 |      debug: 'bool' = False,
 |      log_level: "Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']" = 'INFO',
 |      host: 'str' = '127.0.0.1',
 |      port: 'int' = 8000,
 |      mount_path: 'str' = '/',
 |      sse_path: 'str' = '/sse',
 |      message_path: 'str' = '/messages/',
 |      streamable_http_path: 'str' = '/mcp',
 |      json_response: 'bool' = False,
 |      stateless_http: 'bool' = False,
 |      warn_on_duplicate_resources: 'bool' = True,
 |      warn_on_duplicate_tools: 'bool' = True,
 |      warn_on_duplicate_prompts: 'bool' = True,
 |      dependencies: 'Collection[str]' = (),
 |      lifespan: 'Callable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]] | None' = None,
 |      auth: 'AuthSettings | None' = None,
 |      transport_security: 'TransportSecuritySettings | None' = None
 |  )
 |
 |  Method resolution order:
 |      FastMCP
 |      typing.Generic
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  ____iinniitt____(
 |      self,
 |      name: 'str | None' = None,
 |      instructions: 'str | None' = None,
 |      website_url: 'str | None' = None,
 |      icons: 'list[Icon] | None' = None,
 |      auth_server_provider: 'OAuthAuthorizationServerProvider[Any, Any, Any] | None' = None,
 |      token_verifier: 'TokenVerifier | None' = None,
 |      event_store: 'EventStore | None' = None,
 |      retry_interval: 'int | None' = None,
 |      *,
 |      tools: 'list[Tool] | None' = None,
 |      debug: 'bool' = False,
 |      log_level: "Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']" = 'INFO',
 |      host: 'str' = '127.0.0.1',
 |      port: 'int' = 8000,
 |      mount_path: 'str' = '/',
 |      sse_path: 'str' = '/sse',
 |      message_path: 'str' = '/messages/',
 |      streamable_http_path: 'str' = '/mcp',
 |      json_response: 'bool' = False,
 |      stateless_http: 'bool' = False,
 |      warn_on_duplicate_resources: 'bool' = True,
 |      warn_on_duplicate_tools: 'bool' = True,
 |      warn_on_duplicate_prompts: 'bool' = True,
 |      dependencies: 'Collection[str]' = (),
 |      lifespan: 'Callable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]] | None' = None,
 |      auth: 'AuthSettings | None' = None,
 |      transport_security: 'TransportSecuritySettings | None' = None
 |  )
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  aadddd__pprroommpptt(self, prompt: 'Prompt') -> 'None'
 |      Add a prompt to the server.
 |
 |      Args:
 |          prompt: A Prompt instance to add
 |
 |  aadddd__rreessoouurrccee(self, resource: 'Resource') -> 'None'
 |      Add a resource to the server.
 |
 |      Args:
 |          resource: A Resource instance to add
 |
 |  aadddd__ttooooll(
 |      self,
 |      fn: 'AnyFunction',
 |      name: 'str | None' = None,
 |      title: 'str | None' = None,
 |      description: 'str | None' = None,
 |      annotations: 'ToolAnnotations | None' = None,
 |      icons: 'list[Icon] | None' = None,
 |      meta: 'dict[str, Any] | None' = None,
 |      structured_output: 'bool | None' = None
 |  ) -> 'None'
 |      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:
 |          fn: The function to register as a tool
 |          name: Optional name for the tool (defaults to function name)
 |          title: Optional human-readable title for the tool
 |          description: Optional description of what the tool does
 |          annotations: Optional ToolAnnotations providing additional tool information
 |          structured_output: Controls whether the tool's output is structured or unstructured
 |              - If None, auto-detects based on the function's return type annotation
 |              - If True, creates a structured tool (return type annotation permitting)
 |              - If False, unconditionally creates an unstructured tool
 |
 |  async ccaallll__ttooooll(self, name: 'str', arguments: 'dict[str, Any]') -> 'Sequence[ContentBlock] | dict[str, Any]'
 |      Call a tool by name with arguments.
 |
 |  ccoommpplleettiioonn(self)
 |      Decorator to register a completion handler.
 |
 |      The completion handler receives:
 |      - ref: PromptReference or ResourceTemplateReference
 |      - argument: CompletionArgument with name and partial value
 |      - context: Optional CompletionContext with previously resolved arguments
 |
 |      Example:
 |          @mcp.completion()
 |          async def handle_completion(ref, argument, context):
 |              if isinstance(ref, ResourceTemplateReference):
 |                  # Return completions based on ref, argument, and context
 |                  return Completion(values=["option1", "option2"])
 |              return None
 |
 |  ccuussttoomm__rroouuttee(
 |      self,
 |      path: 'str',
 |      methods: 'list[str]',
 |      name: 'str | None' = None,
 |      include_in_schema: 'bool' = True
 |  )
 |      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.
 |
 |      Routes using this decorator will not require authorization. It is intended
 |      for uses that are either a part of authorization flows or intended to be
 |      public such as health check endpoints.
 |
 |      Args:
 |          path: URL path for the route (e.g., "/oauth/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
 |
 |      Example:
 |          @server.custom_route("/health", methods=["GET"])
 |          async def health_check(request: Request) -> Response:
 |              return JSONResponse({"status": "ok"})
 |
 |  ggeett__ccoonntteexxtt(self) -> 'Context[ServerSession, LifespanResultT, Request]'
 |      Returns a Context object. Note that the context will only be valid
 |      during a request; outside a request, most methods will error.
 |
 |  async ggeett__pprroommpptt(self, name: 'str', arguments: 'dict[str, Any] | None' = None) -> 'GetPromptResult'
 |      Get a prompt by name with arguments.
 |
 |  async lliisstt__pprroommppttss(self) -> 'list[MCPPrompt]'
 |      List all available prompts.
 |
 |  async lliisstt__rreessoouurrccee__tteemmppllaatteess(self) -> 'list[MCPResourceTemplate]'
 |
 |  async lliisstt__rreessoouurrcceess(self) -> 'list[MCPResource]'
 |      List all available resources.
 |
 |  async lliisstt__ttoooollss(self) -> 'list[MCPTool]'
 |      List all available tools.
 |
 |  pprroommpptt(
 |      self,
 |      name: 'str | None' = None,
 |      title: 'str | None' = None,
 |      description: 'str | None' = None,
 |      icons: 'list[Icon] | None' = None
 |  ) -> 'Callable[[AnyFunction], AnyFunction]'
 |      Decorator to register a prompt.
 |
 |              Args:
 |                  name: Optional name for the prompt (defaults to function name)
 |                  title: Optional human-readable title for the prompt
 |                  description: Optional description of what the prompt does
 |
 |              Example:
 |                  @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_file(path: str) -> list[Message]:
 |                      content = await read_file(path)
 |                      return [
 |                          {
 |                              "role": "user",
 |                              "content": {
 |                                  "type": "resource",
 |                                  "resource": {
 |                                      "uri": f"file://{path}",
 |                                      "text": content
 |                                  }
 |                              }
 |                          }
 |                      ]
 |
 |  async rreeaadd__rreessoouurrccee(self, uri: 'AnyUrl | str') -> 'Iterable[ReadResourceContents]'
 |      Read a resource by URI.
 |
 |  rreemmoovvee__ttooooll(self, name: 'str') -> 'None'
 |      Remove a tool from the server by name.
 |
 |      Args:
 |          name: The name of the tool to remove
 |
 |      Raises:
 |          ToolError: If the tool does not exist
 |
 |  rreessoouurrccee(
 |      self,
 |      uri: 'str',
 |      *,
 |      name: 'str | None' = None,
 |      title: 'str | None' = None,
 |      description: 'str | None' = None,
 |      mime_type: 'str | None' = None,
 |      icons: 'list[Icon] | None' = None,
 |      annotations: 'Annotations | None' = None,
 |      meta: 'dict[str, Any] | None' = None
 |  ) -> 'Callable[[AnyFunction], AnyFunction]'
 |      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
 |
 |      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 human-readable title for the resource
 |          description: Optional description of the resource
 |          mime_type: Optional MIME type for the resource
 |          meta: Optional metadata dictionary for the resource
 |
 |      Example:
 |          @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(city: str) -> str:
 |              data = await fetch_weather(city)
 |              return f"Weather for {city}: {data}"
 |
 |  rruunn(
 |      self,
 |      transport: "Literal['stdio', 'sse', 'streamable-http']" = 'stdio',
 |      mount_path: 'str | None' = None
 |  ) -> 'None'
 |      Run the FastMCP server. Note this is a synchronous function.
 |
 |      Args:
 |          transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
 |          mount_path: Optional mount path for SSE transport
 |
 |  async rruunn__ssssee__aassyynncc(self, mount_path: 'str | None' = None) -> 'None'
 |      Run the server using SSE transport.
 |
 |  async rruunn__ssttddiioo__aassyynncc(self) -> 'None'
 |      Run the server using stdio transport.
 |
 |  async rruunn__ssttrreeaammaabbllee__hhttttpp__aassyynncc(self) -> 'None'
 |      Run the server using StreamableHTTP transport.
 |
 |  ssssee__aapppp(self, mount_path: 'str | None' = None) -> 'Starlette'
 |      Return an instance of the SSE server app.
 |
 |  ssttrreeaammaabbllee__hhttttpp__aapppp(self) -> 'Starlette'
 |      Return an instance of the StreamableHTTP server app.
 |
 |  ttooooll(
 |      self,
 |      name: 'str | None' = None,
 |      title: 'str | None' = None,
 |      description: 'str | None' = None,
 |      annotations: 'ToolAnnotations | None' = None,
 |      icons: 'list[Icon] | None' = None,
 |      meta: 'dict[str, Any] | None' = None,
 |      structured_output: 'bool | None' = None
 |  ) -> 'Callable[[AnyFunction], AnyFunction]'
 |      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.
 |
 |      Args:
 |          name: Optional name for the tool (defaults to function name)
 |          title: Optional human-readable title for the tool
 |          description: Optional description of what the tool does
 |          annotations: Optional ToolAnnotations providing additional tool information
 |          structured_output: Controls whether the tool's output is structured or unstructured
 |              - If None, auto-detects based on the function's return type annotation
 |              - If True, creates a structured tool (return type annotation permitting)
 |              - If False, unconditionally creates an unstructured tool
 |
 |      Example:
 |          @server.tool()
 |          def my_tool(x: int) -> str:
 |              return str(x)
 |
 |          @server.tool()
 |          def tool_with_context(x: int, ctx: Context) -> str:
 |              ctx.info(f"Processing {x}")
 |              return str(x)
 |
 |          @server.tool()
 |          async def async_tool(x: int, context: Context) -> str:
 |              await context.report_progress(50, 100)
 |              return str(x)
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  iiccoonnss
 |
 |  iinnssttrruuccttiioonnss
 |
 |  nnaammee
 |
 |  sseessssiioonn__mmaannaaggeerr
 |      Get the StreamableHTTP session manager.
 |
 |      This is exposed to enable advanced use cases like mounting multiple
 |      FastMCP servers in a single FastAPI application.
 |
 |      Raises:
 |          RuntimeError: If called before streamable_http_app() has been called.
 |
 |  wweebbssiittee__uurrll
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  ____ddiicctt____
 |      dictionary for instance variables
 |
 |  ____wweeaakkrreeff____
 |      list of weak references to the object
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  ____aannnnoottaattiioonnss____ = {}
 |
 |  ____oorriigg__bbaasseess____ = (typing.Generic[~LifespanResultT],)
 |
 |  ____ppaarraammeetteerrss____ = (~LifespanResultT,)
 |
 |  ----------------------------------------------------------------------
 |  Class methods inherited from typing.Generic:
 |
 |  ____ccllaassss__ggeettiitteemm____(...)
 |      Parameterizes a generic class.
 |
 |      At least, parameterizing a generic class is the *main* thing this
 |      method does. For example, for some generic class `Foo`, this is called
 |      when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
 |
 |      However, note that this method is also called when defining generic
 |      classes in the first place with `class Foo[T]: ...`.
 |
 |  ____iinniitt__ssuubbccllaassss____(...)
 |      Function to initialize subclasses.
