mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-21 21:14:17 +02:00
use type
This commit is contained in:
parent
a62c562204
commit
16af43e272
9 changed files with 46 additions and 50 deletions
|
|
@ -9,7 +9,6 @@ the ToolManager's import_tools functionality. It shows how to:
|
|||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Dict, List
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
|
|
@ -34,7 +33,7 @@ news_app = FastMCP("News App")
|
|||
|
||||
|
||||
@news_app.tool()
|
||||
def get_news_headlines() -> List[str]:
|
||||
def get_news_headlines() -> list[str]:
|
||||
"""Get the latest news headlines."""
|
||||
return [
|
||||
"Tech company launches new product",
|
||||
|
|
@ -58,7 +57,7 @@ app = FastMCP("Main App")
|
|||
|
||||
|
||||
@app.tool()
|
||||
def check_app_status() -> Dict[str, str]:
|
||||
def check_app_status() -> dict[str, str]:
|
||||
"""Check the status of the main application."""
|
||||
return {"status": "running", "version": "1.0.0", "uptime": "3h 24m"}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import datetime
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncContextManager
|
||||
from typing import Any
|
||||
|
||||
import mcp.types
|
||||
from mcp import ClientSession
|
||||
|
|
@ -48,7 +49,7 @@ class Client:
|
|||
):
|
||||
self.transport = infer_transport(transport)
|
||||
self._session: ClientSession | None = None
|
||||
self._session_cm: AsyncContextManager[ClientSession] | None = None
|
||||
self._session_cm: AbstractAsyncContextManager[ClientSession] | None = None
|
||||
|
||||
# Store common kwargs to pass to transport.connect_session
|
||||
if roots is not None and list_roots_callback is not None:
|
||||
|
|
|
|||
|
|
@ -2,14 +2,10 @@ import abc
|
|||
import contextlib
|
||||
import datetime
|
||||
import os
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
AsyncIterator,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
TypedDict,
|
||||
Union,
|
||||
)
|
||||
|
||||
from mcp import ClientSession, StdioServerParameters
|
||||
|
|
@ -103,7 +99,7 @@ class WSTransport(ClientTransport):
|
|||
class SSETransport(ClientTransport):
|
||||
"""Transport implementation that connects to an MCP server via Server-Sent Events."""
|
||||
|
||||
def __init__(self, url: str | AnyUrl, headers: Optional[Dict[str, str]] = None):
|
||||
def __init__(self, url: str | AnyUrl, headers: dict[str, str] | None = None):
|
||||
if isinstance(url, AnyUrl):
|
||||
url = str(url)
|
||||
if not isinstance(url, str) or not url.startswith("http"):
|
||||
|
|
@ -138,9 +134,9 @@ class StdioTransport(ClientTransport):
|
|||
def __init__(
|
||||
self,
|
||||
command: str,
|
||||
args: List[str],
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
cwd: Optional[str] = None,
|
||||
args: list[str],
|
||||
env: dict[str, str] | None = None,
|
||||
cwd: str | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize a Stdio transport.
|
||||
|
|
@ -182,10 +178,10 @@ class PythonStdioTransport(StdioTransport):
|
|||
|
||||
def __init__(
|
||||
self,
|
||||
script_path: Union[str, Path],
|
||||
args: Optional[List[str]] = None,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
cwd: Optional[str] = None,
|
||||
script_path: str | Path,
|
||||
args: list[str] | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
cwd: str | None = None,
|
||||
python_cmd: str = "python",
|
||||
):
|
||||
"""
|
||||
|
|
@ -217,10 +213,10 @@ class NodeStdioTransport(StdioTransport):
|
|||
|
||||
def __init__(
|
||||
self,
|
||||
script_path: Union[str, Path],
|
||||
args: Optional[List[str]] = None,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
cwd: Optional[str] = None,
|
||||
script_path: str | Path,
|
||||
args: list[str] | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
cwd: str | None = None,
|
||||
node_cmd: str = "node",
|
||||
):
|
||||
"""
|
||||
|
|
@ -253,12 +249,12 @@ class UvxStdioTransport(StdioTransport):
|
|||
def __init__(
|
||||
self,
|
||||
tool_name: str,
|
||||
tool_args: Optional[List[str]] = None,
|
||||
project_directory: Optional[str] = None,
|
||||
python_version: Optional[str] = None,
|
||||
with_packages: Optional[List[str]] = None,
|
||||
from_package: Optional[str] = None,
|
||||
env_vars: Optional[Dict[str, str]] = None,
|
||||
tool_args: list[str] | None = None,
|
||||
project_directory: str | None = None,
|
||||
python_version: str | None = None,
|
||||
with_packages: list[str] | None = None,
|
||||
from_package: str | None = None,
|
||||
env_vars: dict[str, str] | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize a Uvx transport.
|
||||
|
|
@ -308,9 +304,9 @@ class NpxStdioTransport(StdioTransport):
|
|||
def __init__(
|
||||
self,
|
||||
package: str,
|
||||
args: Optional[List[str]] = None,
|
||||
project_directory: Optional[str] = None,
|
||||
env_vars: Optional[Dict[str, str]] = None,
|
||||
args: list[str] | None = None,
|
||||
project_directory: str | None = None,
|
||||
env_vars: dict[str, str] | None = None,
|
||||
use_package_lock: bool = True,
|
||||
):
|
||||
"""
|
||||
|
|
@ -394,7 +390,7 @@ def infer_transport(
|
|||
return FastMCPTransport(mcp=transport)
|
||||
|
||||
# the transport is a path to a script
|
||||
elif isinstance(transport, (Path, str)) and Path(transport).exists():
|
||||
elif isinstance(transport, Path | str) and Path(transport).exists():
|
||||
if str(transport).endswith(".py"):
|
||||
return PythonStdioTransport(script_path=transport)
|
||||
elif str(transport).endswith(".js"):
|
||||
|
|
@ -403,11 +399,11 @@ def infer_transport(
|
|||
raise ValueError(f"Unsupported script type: {transport}")
|
||||
|
||||
# the transport is an http(s) URL
|
||||
elif isinstance(transport, (AnyUrl, str)) and str(transport).startswith("http"):
|
||||
elif isinstance(transport, AnyUrl | str) and str(transport).startswith("http"):
|
||||
return SSETransport(url=transport)
|
||||
|
||||
# the transport is a websocket URL
|
||||
elif isinstance(transport, (AnyUrl, str)) and str(transport).startswith("ws"):
|
||||
elif isinstance(transport, AnyUrl | str) and str(transport).startswith("ws"):
|
||||
return WSTransport(url=transport)
|
||||
|
||||
# the transport is an unknown type
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ import enum
|
|||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal, Pattern
|
||||
from re import Pattern
|
||||
from typing import Any, Literal
|
||||
|
||||
import httpx
|
||||
from pydantic.networks import AnyUrl
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ class FastMCP(Generic[LifespanResultT]):
|
|||
self.dependencies = self.settings.dependencies
|
||||
|
||||
# Setup for mounted apps
|
||||
self._mounted_apps: dict[str, "FastMCP"] = {}
|
||||
self._mounted_apps: dict[str, FastMCP] = {}
|
||||
|
||||
# Set up MCP protocol handlers
|
||||
self._setup_handlers()
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ class ToolManager:
|
|||
return await tool.run(arguments, context=context)
|
||||
|
||||
def import_tools(
|
||||
self, tool_manager: "ToolManager", prefix: str | None = None
|
||||
self, tool_manager: ToolManager, prefix: str | None = None
|
||||
) -> None:
|
||||
"""
|
||||
Import all tools from another ToolManager with prefixed names.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"""Tests for the OpenAPI parsing utilities."""
|
||||
|
||||
from typing import Any, Dict
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from fastapi import Body, FastAPI, Path, Query
|
||||
|
|
@ -12,7 +12,7 @@ from fastmcp.utilities.openapi import parse_openapi_to_http_routes
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def petstore_schema() -> Dict[str, Any]:
|
||||
def petstore_schema() -> dict[str, Any]:
|
||||
"""Fixture that returns a simple Pet Store API schema."""
|
||||
return {
|
||||
"openapi": "3.1.0",
|
||||
|
|
@ -109,7 +109,7 @@ def parsed_petstore_routes(petstore_schema):
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def bookstore_schema() -> Dict[str, Any]:
|
||||
def bookstore_schema() -> dict[str, Any]:
|
||||
"""Fixture that returns a Book Store API schema with different parameter types."""
|
||||
return {
|
||||
"openapi": "3.1.0",
|
||||
|
|
@ -292,7 +292,7 @@ def fastapi_app() -> FastAPI:
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def fastapi_openapi_schema(fastapi_app) -> Dict[str, Any]:
|
||||
def fastapi_openapi_schema(fastapi_app) -> dict[str, Any]:
|
||||
"""Fixture that returns the OpenAPI schema of the FastAPI app."""
|
||||
return fastapi_app.openapi()
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"""Tests for advanced features of the OpenAPI utilities."""
|
||||
|
||||
from typing import Any, Dict
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
|
|
@ -8,7 +8,7 @@ from fastmcp.utilities.openapi import parse_openapi_to_http_routes
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def complex_schema() -> Dict[str, Any]:
|
||||
def complex_schema() -> dict[str, Any]:
|
||||
"""Fixture that returns a complex OpenAPI schema with nested references."""
|
||||
return {
|
||||
"openapi": "3.1.0",
|
||||
|
|
@ -167,7 +167,7 @@ def complex_route_map(parsed_complex_routes):
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def schema_with_invalid_reference() -> Dict[str, Any]:
|
||||
def schema_with_invalid_reference() -> dict[str, Any]:
|
||||
"""Fixture that returns a schema with an invalid reference."""
|
||||
return {
|
||||
"openapi": "3.1.0",
|
||||
|
|
@ -191,7 +191,7 @@ def schema_with_invalid_reference() -> Dict[str, Any]:
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def schema_with_content_params() -> Dict[str, Any]:
|
||||
def schema_with_content_params() -> dict[str, Any]:
|
||||
"""Fixture that returns a schema with content-based parameters (complex parameters)."""
|
||||
return {
|
||||
"openapi": "3.1.0",
|
||||
|
|
@ -236,7 +236,7 @@ def parsed_content_param_routes(schema_with_content_params):
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def schema_all_http_methods() -> Dict[str, Any]:
|
||||
def schema_all_http_methods() -> dict[str, Any]:
|
||||
"""Fixture that returns a schema with all HTTP methods."""
|
||||
return {
|
||||
"openapi": "3.1.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"""Tests for FastAPI integration with the OpenAPI utilities."""
|
||||
|
||||
from typing import Any, Dict
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
|
@ -12,7 +12,6 @@ from fastmcp.utilities.openapi import parse_openapi_to_http_routes
|
|||
def fastapi_server() -> FastAPI:
|
||||
"""Fixture that returns a FastAPI app for live OpenAPI schema testing."""
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
|
||||
from fastapi import Body, Depends, Header, HTTPException, Path, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
|
@ -145,7 +144,7 @@ def fastapi_server() -> FastAPI:
|
|||
)
|
||||
async def update_item_tags(
|
||||
item_id: int = Path(..., description="The ID of the item"),
|
||||
tags: List[str] = Body(..., description="Updated tags"),
|
||||
tags: list[str] = Body(..., description="Updated tags"),
|
||||
):
|
||||
"""Update just the tags of an item."""
|
||||
return {"item_id": item_id, "tags": tags}
|
||||
|
|
@ -229,7 +228,7 @@ def fastapi_server() -> FastAPI:
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def fastapi_openapi_schema(fastapi_server) -> Dict[str, Any]:
|
||||
def fastapi_openapi_schema(fastapi_server) -> dict[str, Any]:
|
||||
"""Fixture that returns the OpenAPI schema from a live FastAPI server."""
|
||||
return fastapi_server.openapi()
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue