Use 120 characters instead of 88 (#856)

This commit is contained in:
Marcelo Trylesinski 2025-06-11 02:45:50 -07:00 • committed by GitHub
commit 543961968c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -97,9 +97,7 @@ class Settings(BaseSettings, Generic[LifespanResultT]):
# StreamableHTTP settings
json_response: bool = False
stateless_http: bool = (
False # If True, uses true stateless mode (new transport per request)
)
stateless_http: bool = False # If True, uses true stateless mode (new transport per request)
# resource settings
warn_on_duplicate_resources: bool = True
@ -115,9 +113,9 @@ class Settings(BaseSettings, Generic[LifespanResultT]):
description="List of dependencies to install in the server environment",
)
lifespan: (
Callable[[FastMCP], AbstractAsyncContextManager[LifespanResultT]] | None
) = Field(None, description="Lifespan context manager")
lifespan: Callable[[FastMCP], AbstractAsyncContextManager[LifespanResultT]] | None = Field(
None, description="Lifespan context manager"
)
auth: AuthSettings | None = None
@ -125,9 +123,7 @@ class Settings(BaseSettings, Generic[LifespanResultT]):
def lifespan_wrapper(
app: FastMCP,
lifespan: Callable[[FastMCP], AbstractAsyncContextManager[LifespanResultT]],
) -> Callable[
[MCPServer[LifespanResultT, Request]], AbstractAsyncContextManager[object]
]:
) -> Callable[[MCPServer[LifespanResultT, Request]], AbstractAsyncContextManager[object]]:
@asynccontextmanager
async def wrap(s: MCPServer[LifespanResultT, Request]) -> AsyncIterator[object]:
async with lifespan(app) as context:
@ -141,8 +137,7 @@ class FastMCP:
self,
name: str | None = None,
instructions: str | None = None,
auth_server_provider: OAuthAuthorizationServerProvider[Any, Any, Any]
| None = None,
auth_server_provider: OAuthAuthorizationServerProvider[Any, Any, Any] | None = None,
event_store: EventStore | None = None,
*,
tools: list[Tool] | None = None,
@ -153,31 +148,18 @@ class FastMCP:
self._mcp_server = MCPServer(
name=name or "FastMCP",
instructions=instructions,
lifespan=(
lifespan_wrapper(self, self.settings.lifespan)
if self.settings.lifespan
else default_lifespan
),
)
self._tool_manager = ToolManager(
tools=tools, warn_on_duplicate_tools=self.settings.warn_on_duplicate_tools
)
self._resource_manager = ResourceManager(
warn_on_duplicate_resources=self.settings.warn_on_duplicate_resources
)
self._prompt_manager = PromptManager(
warn_on_duplicate_prompts=self.settings.warn_on_duplicate_prompts
lifespan=(lifespan_wrapper(self, self.settings.lifespan) if self.settings.lifespan else default_lifespan),
)
self._tool_manager = ToolManager(tools=tools, warn_on_duplicate_tools=self.settings.warn_on_duplicate_tools)
self._resource_manager = ResourceManager(warn_on_duplicate_resources=self.settings.warn_on_duplicate_resources)
self._prompt_manager = PromptManager(warn_on_duplicate_prompts=self.settings.warn_on_duplicate_prompts)
if (self.settings.auth is not None) != (auth_server_provider is not None):
# TODO: after we support separate authorization servers (see
# https://github.com/modelcontextprotocol/modelcontextprotocol/pull/284)
# we should validate that if auth is enabled, we have either an
# auth_server_provider to host our own authorization server,
# OR the URL of a 3rd party authorization server.
raise ValueError(
"settings.auth must be specified if and only if auth_server_provider "
"is specified"
)
raise ValueError("settings.auth must be specified if and only if auth_server_provider " "is specified")
self._auth_server_provider = auth_server_provider
self._event_store = event_store
self._custom_starlette_routes: list[Route] = []
@ -340,9 +322,7 @@ class FastMCP:
description: Optional description of what the tool does
annotations: Optional ToolAnnotations providing additional tool information
"""
self._tool_manager.add_tool(
fn, name=name, description=description, annotations=annotations
)
self._tool_manager.add_tool(fn, name=name, description=description, annotations=annotations)
def tool(
self,
@ -379,14 +359,11 @@ class FastMCP:
# Check if user passed function directly instead of calling decorator
if callable(name):
raise TypeError(
"The @tool decorator was used incorrectly. "
"Did you forget to call it? Use @tool() instead of @tool"
"The @tool decorator was used incorrectly. " "Did you forget to call it? Use @tool() instead of @tool"
)
def decorator(fn: AnyFunction) -> AnyFunction:
self.add_tool(
fn, name=name, description=description, annotations=annotations
)
self.add_tool(fn, name=name, description=description, annotations=annotations)
return fn
return decorator
@ -462,8 +439,7 @@ class FastMCP:
if uri_params != func_params:
raise ValueError(
f"Mismatch between URI parameters {uri_params} "
f"and function parameters {func_params}"
f"Mismatch between URI parameters {uri_params} " f"and function parameters {func_params}"
)
# Register as template
@ -496,9 +472,7 @@ class FastMCP:
"""
self._prompt_manager.add_prompt(prompt)
def prompt(
self, name: str | None = None, description: str | None = None
) -> Callable[[AnyFunction], AnyFunction]:
def prompt(self, name: str | None = None, description: str | None = None) -> Callable[[AnyFunction], AnyFunction]:
"""Decorator to register a prompt.
Args:
@ -665,9 +639,7 @@ class FastMCP:
self.settings.mount_path = mount_path
# Create normalized endpoint considering the mount path
normalized_message_endpoint = self._normalize_path(
self.settings.mount_path, self.settings.message_path
)
normalized_message_endpoint = self._normalize_path(self.settings.mount_path, self.settings.message_path)
# Set up auth context and dependencies
@ -764,9 +736,7 @@ class FastMCP:
routes.extend(self._custom_starlette_routes)
# Create Starlette app with routes and middleware
return Starlette(
debug=self.settings.debug, routes=routes, middleware=middleware
)
return Starlette(debug=self.settings.debug, routes=routes, middleware=middleware)
def streamable_http_app(self) -> Starlette:
"""Return an instance of the StreamableHTTP server app."""
@ -783,9 +753,7 @@ class FastMCP:
)
# Create the ASGI handler
async def handle_streamable_http(
scope: Scope, receive: Receive, send: Send
) -> None:
async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None:
await self.session_manager.handle_request(scope, receive, send)
# Create routes
@ -861,9 +829,7 @@ class FastMCP:
for prompt in prompts
]
async def get_prompt(
self, name: str, arguments: dict[str, Any] | None = None
) -> GetPromptResult:
async def get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult:
"""Get a prompt by name with arguments."""
try:
messages = await self._prompt_manager.render_prompt(name, arguments)
@ -936,9 +902,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT, RequestT]):
def __init__(
self,
*,
request_context: (
RequestContext[ServerSessionT, LifespanContextT, RequestT] | None
) = None,
request_context: (RequestContext[ServerSessionT, LifespanContextT, RequestT] | None) = None,
fastmcp: FastMCP | None = None,
**kwargs: Any,
):
@ -962,9 +926,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT, RequestT]):
raise ValueError("Context is not available outside of a request")
return self._request_context
async def report_progress(
self, progress: float, total: float | None = None, message: str | None = None
) -> None:
async def report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None:
"""Report progress for the current operation.
Args:
@ -972,11 +934,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT, RequestT]):
total: Optional total value e.g. 100
message: Optional message e.g. Starting render...
"""
progress_token = (
self.request_context.meta.progressToken
if self.request_context.meta
else None
)
progress_token = self.request_context.meta.progressToken if self.request_context.meta else None
if progress_token is None:
return
@ -997,9 +955,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT, RequestT]):
Returns:
The resource content as either text or bytes
"""
assert (
self._fastmcp is not None
), "Context is not available outside of a request"
assert self._fastmcp is not None, "Context is not available outside of a request"
return await self._fastmcp.read_resource(uri)
async def log(
@ -1027,11 +983,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT, RequestT]):
@property
def client_id(self) -> str | None:
"""Get the client ID if available."""
return (
getattr(self.request_context.meta, "client_id", None)
if self.request_context.meta
else None
)
return getattr(self.request_context.meta, "client_id", None) if self.request_context.meta else None
@property
def request_id(self) -> str: