fastbridge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fastbridge/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """FastBridge: expose web endpoints as MCP and UTCP tools.
2
+
3
+ This package is framework-neutral and only holds the markers. Each framework
4
+ adapter lives in its own subpackage and is imported explicitly:
5
+
6
+ - ``fastbridge.fastapi`` (also plain Starlette)
7
+ - ``fastbridge.django``
8
+ - ``fastbridge.litestar``
9
+ """
10
+
11
+ from .decorators import hidden, tool
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = ["__version__", "hidden", "tool"]
@@ -0,0 +1,47 @@
1
+ """Optional markers. Level 0 (`bridge(app)`) needs none of these."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TypeVar
6
+
7
+ F = TypeVar("F")
8
+
9
+
10
+ def tool(fn: F) -> F:
11
+ """Mark an endpoint for exposure when the app is bridged with ``mode="opt-in"``.
12
+
13
+ Takes no arguments and returns the endpoint unchanged, so it composes with
14
+ any other decorator. Place it **below** the framework's route decorator;
15
+ above it, the router would already have registered the unmarked function.
16
+
17
+ Example:
18
+ ```python
19
+ @app.get("/items/{item_id}")
20
+ @tool
21
+ def get_item(item_id: int): ...
22
+ ```
23
+
24
+ Args:
25
+ fn: The endpoint function, or a class-based view.
26
+
27
+ Returns:
28
+ ``fn``, with a marker attribute set.
29
+ """
30
+ fn.__fastbridge__ = True # type: ignore[attr-defined]
31
+ return fn
32
+
33
+
34
+ def hidden(fn: F) -> F:
35
+ """Never expose this endpoint, in any mode.
36
+
37
+ Use it to keep an endpoint out of MCP and UTCP when the app is bridged with
38
+ the default ``mode="all"``. Place it below the framework's route decorator.
39
+
40
+ Args:
41
+ fn: The endpoint function, or a class-based view.
42
+
43
+ Returns:
44
+ ``fn``, with a marker attribute set.
45
+ """
46
+ fn.__fastbridge_hidden__ = True # type: ignore[attr-defined]
47
+ return fn
@@ -0,0 +1 @@
1
+ """Django adapter. Add "fastbridge.django" to INSTALLED_APPS; nothing else is required."""
@@ -0,0 +1,17 @@
1
+ from django.apps import AppConfig
2
+ from django.conf import settings
3
+
4
+ MIDDLEWARE = "fastbridge.django.middleware.BridgeMiddleware"
5
+
6
+
7
+ class FastBridgeConfig(AppConfig):
8
+ """App config that installs :class:`~fastbridge.django.middleware.BridgeMiddleware`."""
9
+
10
+ name = "fastbridge.django"
11
+ label = "fastbridge"
12
+
13
+ def ready(self):
14
+ # Level 0: put the bridge first in the chain so users edit nothing but INSTALLED_APPS.
15
+ # Skip if the user already placed it themselves.
16
+ if MIDDLEWARE not in settings.MIDDLEWARE:
17
+ settings.MIDDLEWARE = [MIDDLEWARE, *settings.MIDDLEWARE]
@@ -0,0 +1,106 @@
1
+ """Discover tools by walking Django's URL resolver (no schema exists, so we infer)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Collection, Iterator
7
+
8
+ from django.conf import settings
9
+ from django.urls import get_resolver
10
+ from django.urls.resolvers import RoutePattern, URLPattern, URLResolver
11
+
12
+ from ..ir import Param, ToolSpec
13
+ from ..naming import slug
14
+
15
+ _CONVERTOR_SCHEMA = { # keyed by converter class name minus "Converter"
16
+ "int": {"type": "integer"},
17
+ "uuid": {"type": "string", "format": "uuid"},
18
+ }
19
+ _HTTP = ("get", "post", "put", "patch", "delete")
20
+ _BODY = {"POST", "PUT", "PATCH"}
21
+ _SAFE = {"GET", "HEAD", "OPTIONS"}
22
+ _UNSUPPORTED_REGEX = re.compile(r"[()\[\]*+?\\|]")
23
+
24
+
25
+ def _route_str(pattern) -> str | None:
26
+ """Render a pattern as '/x/{name}/'; None if it can't be expressed (e.g. unnamed regex groups)."""
27
+ s = str(pattern)
28
+ if isinstance(pattern, RoutePattern):
29
+ return re.sub(r"<(?:\w+:)?(\w+)>", r"{\1}", s)
30
+ s = re.sub(r"\(\?P<(\w+)>[^)]*\)", r"{\1}", s).removeprefix("^").removesuffix("$").removesuffix("\\Z")
31
+ return None if _UNSUPPORTED_REGEX.search(re.sub(r"\{\w+\}", "", s)) else s
32
+
33
+
34
+ def _walk(patterns, prefix: str = "", converters: dict | None = None) -> Iterator[tuple[str, URLPattern, dict]]:
35
+ converters = converters or {}
36
+ for p in patterns:
37
+ if isinstance(p, URLResolver):
38
+ if p.app_name == "admin": # never expose the admin site
39
+ continue
40
+ part = _route_str(p.pattern)
41
+ if part is not None:
42
+ yield from _walk(p.url_patterns, prefix + part, {**converters, **getattr(p.pattern, "converters", {})})
43
+ elif isinstance(p, URLPattern):
44
+ part = _route_str(p.pattern)
45
+ if part is not None:
46
+ yield prefix + part, p, {**converters, **getattr(p.pattern, "converters", {})}
47
+
48
+
49
+ def _targets(cb):
50
+ """Objects a marker may live on: the view function and/or its class."""
51
+ return [cb, getattr(cb, "view_class", None), getattr(cb, "cls", None)]
52
+
53
+
54
+ def _methods_and_doc(cb) -> list[tuple[str, str]]:
55
+ """[(HTTP method, description)]. Function views don't declare methods, so we assume GET."""
56
+ cls = getattr(cb, "view_class", None) or getattr(cb, "cls", None)
57
+ if cls is None:
58
+ return [("GET", (cb.__doc__ or "").strip())]
59
+ actions = getattr(cb, "actions", None) # DRF viewsets: {"get": "list", ...}
60
+ out = []
61
+ for m in actions or {m: m for m in _HTTP}:
62
+ handler = getattr(cls, actions[m] if actions else m, None)
63
+ if m in _HTTP and handler is not None:
64
+ out.append((m.upper(), (getattr(handler, "__doc__", None) or cls.__doc__ or "").strip()))
65
+ return out
66
+
67
+
68
+ def discover_django(*, mode: str = "all", exclude_paths: Collection[str] = (), urlconf=None) -> list[ToolSpec]:
69
+ tools: list[ToolSpec] = []
70
+ seen: set[str] = set()
71
+ csrf_on = "django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE
72
+ for path, p, conv in _walk(get_resolver(urlconf).url_patterns):
73
+ full = "/" + path.lstrip("/")
74
+ if full in exclude_paths:
75
+ continue
76
+ cb = p.callback
77
+ marked = [t for t in _targets(cb) if t is not None]
78
+ if any(getattr(t, "__fastbridge_hidden__", False) for t in marked):
79
+ continue
80
+ if mode == "opt-in" and not any(getattr(t, "__fastbridge__", False) for t in marked):
81
+ continue
82
+ params = [
83
+ Param(
84
+ name,
85
+ "path",
86
+ dict(
87
+ _CONVERTOR_SCHEMA.get(
88
+ type(conv.get(name)).__name__.removesuffix("Converter").lower(), {"type": "string"}
89
+ )
90
+ ),
91
+ True,
92
+ )
93
+ for name in re.findall(r"\{(\w+)\}", full)
94
+ ]
95
+ methods = _methods_and_doc(cb)
96
+ base = p.name or getattr(getattr(cb, "view_class", None), "__name__", None) or cb.__name__
97
+ for method, doc in methods:
98
+ name = base if len(methods) == 1 else f"{base}_{method.lower()}"
99
+ if name in seen:
100
+ name = slug(method, full)
101
+ seen.add(name)
102
+ body = {"type": "object", "description": "JSON request body"} if method in _BODY else None
103
+ # A direct (UTCP) call to an unsafe-method view is rejected by CSRF unless the view is csrf_exempt.
104
+ direct = not (csrf_on and method not in _SAFE and not any(getattr(t, "csrf_exempt", False) for t in marked))
105
+ tools.append(ToolSpec(name, doc, method, full, list(params), body, free_query=True, utcp_callable=direct))
106
+ return tools
@@ -0,0 +1,98 @@
1
+ """Serves /utcp and /mcp from inside the Django middleware chain.
2
+
3
+ Tool calls are dispatched through the *rest* of the chain (sessions, auth,
4
+ your own middleware, then the view), so permissions behave exactly as for a
5
+ normal request. CSRF is skipped for these internal requests only: /mcp itself
6
+ requires Content-Type: application/json, which a cross-site form cannot send.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from urllib.parse import urlencode
13
+
14
+ from asgiref.sync import markcoroutinefunction
15
+ from django.conf import settings
16
+ from django.http import HttpResponse, JsonResponse
17
+ from django.test import RequestFactory
18
+
19
+ from ..executor import ToolError, fill_path, split_args
20
+ from ..protocols import FORWARD_HEADERS, is_json_content_type, mcp_handle, utcp_manual
21
+ from .discovery import discover_django
22
+
23
+
24
+ class BridgeMiddleware:
25
+ """Serves ``/utcp`` and ``/mcp`` and dispatches MCP tool calls through the rest of the chain.
26
+
27
+ Normally installed for you by adding ``"fastbridge.django"`` to
28
+ ``INSTALLED_APPS``. Add it to ``MIDDLEWARE`` yourself only if you need to
29
+ control its position; it is async-only and Django adapts it for WSGI.
30
+
31
+ Configure it with the ``FASTBRIDGE`` setting (``mode``, ``mcp_path``,
32
+ ``utcp_path``).
33
+ """
34
+
35
+ sync_capable = False # Django adapts it for WSGI automatically
36
+ async_capable = True
37
+
38
+ def __init__(self, get_response):
39
+ self.get_response = get_response
40
+ markcoroutinefunction(self)
41
+ cfg = getattr(settings, "FASTBRIDGE", {})
42
+ self.mode = cfg.get("mode", "all")
43
+ self.mcp_path = cfg.get("mcp_path", "/mcp")
44
+ self.utcp_path = cfg.get("utcp_path", "/utcp")
45
+
46
+ def _tools(self):
47
+ return discover_django(mode=self.mode, exclude_paths={self.mcp_path, self.utcp_path})
48
+
49
+ async def __call__(self, request):
50
+ if request.path == self.utcp_path and request.method == "GET":
51
+ return JsonResponse(utcp_manual(self._tools(), request.build_absolute_uri("/")))
52
+ if request.path == self.mcp_path:
53
+ if request.method != "POST":
54
+ return HttpResponse(status=405, headers={"Allow": "POST"})
55
+ return await self._mcp(request)
56
+ return await self.get_response(request)
57
+
58
+ async def _mcp(self, request):
59
+ if not is_json_content_type(request.headers.get("content-type", "")):
60
+ return JsonResponse({"error": "Content-Type must be application/json"}, status=415)
61
+ try:
62
+ msg = json.loads(request.body)
63
+ except ValueError:
64
+ return JsonResponse(
65
+ {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}, status=400
66
+ )
67
+ fwd = {k: v for k, v in request.headers.items() if k.lower() in FORWARD_HEADERS}
68
+ host = request.get_host()
69
+
70
+ async def call(tool, args):
71
+ return await self._call(tool, args, fwd, host)
72
+
73
+ reply = await mcp_handle(self._tools(), msg, call)
74
+ return HttpResponse(status=202) if reply is None else JsonResponse(reply)
75
+
76
+ async def _call(self, tool, args, fwd, host):
77
+ path_args, query, headers, body = split_args(tool, args)
78
+ extra = {"HTTP_HOST": host, "QUERY_STRING": urlencode(query, doseq=True)}
79
+ for k, v in {**fwd, **headers}.items():
80
+ extra["HTTP_" + k.upper().replace("-", "_")] = str(v)
81
+ req = RequestFactory().generic(
82
+ tool.method,
83
+ fill_path(tool, path_args),
84
+ data=json.dumps(body) if body is not None else "",
85
+ content_type="application/json" if body is not None else "application/octet-stream",
86
+ **extra,
87
+ )
88
+ req._dont_enforce_csrf_checks = True # honoured by CsrfViewMiddleware
89
+ resp = await self.get_response(req)
90
+ if getattr(resp, "streaming", False):
91
+ payload = "<streaming response not supported>"
92
+ elif "json" in resp.get("Content-Type", ""):
93
+ payload = json.loads(resp.content or b"null")
94
+ else:
95
+ payload = resp.content.decode(resp.charset or "utf-8", "replace")
96
+ if resp.status_code >= 300: # includes login redirects
97
+ raise ToolError(resp.status_code, payload)
98
+ return payload
fastbridge/executor.py ADDED
@@ -0,0 +1,69 @@
1
+ """Call a tool by dispatching a real request through the app's own ASGI stack,
2
+ so middleware, auth, dependencies and validation all still apply."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from urllib.parse import quote
7
+
8
+ import httpx
9
+
10
+ from .ir import ToolSpec
11
+
12
+
13
+ class ToolError(Exception):
14
+ """An endpoint answered with an HTTP error (status 400 or above).
15
+
16
+ Over MCP this becomes a normal tool result with ``isError: true``.
17
+
18
+ Attributes:
19
+ status: The HTTP status code.
20
+ payload: The decoded response body.
21
+ """
22
+
23
+ def __init__(self, status: int, payload):
24
+ super().__init__(f"HTTP {status}")
25
+ self.status, self.payload = status, payload
26
+
27
+
28
+ def split_args(tool: ToolSpec, args: dict) -> tuple[dict, dict, dict, object]:
29
+ path: dict = {}
30
+ query: dict = {}
31
+ headers: dict = {}
32
+ known = {p.name for p in tool.params}
33
+ for p in tool.params:
34
+ if p.name in args:
35
+ {"path": path, "query": query, "header": headers}[p.location][p.name] = args[p.name]
36
+ rest = {k: v for k, v in args.items() if k not in known}
37
+ if tool.free_query and isinstance(rest.get("query"), dict):
38
+ query.update(rest.pop("query"))
39
+ if tool.body is None:
40
+ body = None
41
+ elif tool.body_is_flat:
42
+ body = rest or None
43
+ else:
44
+ body = rest.get("body")
45
+ return path, query, headers, body
46
+
47
+
48
+ def fill_path(tool: ToolSpec, path_args: dict) -> str:
49
+ url = tool.path
50
+ for k, v in path_args.items():
51
+ url = url.replace("{" + k + "}", quote(str(v), safe="/"))
52
+ return url
53
+
54
+
55
+ async def invoke(app, tool: ToolSpec, args: dict, forward_headers: dict | None = None):
56
+ path_args, query, headers, body = split_args(tool, args)
57
+ url = fill_path(tool, path_args)
58
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://fastbridge.local") as c:
59
+ r = await c.request(
60
+ tool.method,
61
+ url,
62
+ params=query,
63
+ json=body,
64
+ headers={**(forward_headers or {}), **{k: str(v) for k, v in headers.items()}},
65
+ )
66
+ payload = r.json() if "json" in r.headers.get("content-type", "") else r.text
67
+ if r.status_code >= 400:
68
+ raise ToolError(r.status_code, payload)
69
+ return payload
@@ -0,0 +1,5 @@
1
+ """FastAPI adapter (also works for plain Starlette apps): `from fastbridge.fastapi import bridge`."""
2
+
3
+ from .bridge import bridge
4
+
5
+ __all__ = ["bridge"]
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TypeVar
4
+
5
+ from starlette.applications import Starlette
6
+ from starlette.requests import Request
7
+ from starlette.responses import JSONResponse, Response
8
+ from starlette.routing import Route
9
+
10
+ from ..executor import invoke
11
+ from ..protocols import FORWARD_HEADERS, is_json_content_type, mcp_handle, utcp_manual
12
+ from .discovery import discover
13
+
14
+ AppT = TypeVar("AppT", bound=Starlette) # FastAPI is a Starlette subclass
15
+
16
+
17
+ def bridge(app: AppT, *, mode: str = "all", mcp_path: str = "/mcp", utcp_path: str = "/utcp") -> AppT:
18
+ """Add `/mcp` and `/utcp` to a FastAPI or Starlette app.
19
+
20
+ Discovery is lazy (it runs on every request), so endpoints registered after
21
+ this call are exposed too.
22
+
23
+ Args:
24
+ app: The application to bridge.
25
+ mode: ``"all"`` exposes every endpoint except those marked
26
+ ``@hidden``. ``"opt-in"`` exposes only endpoints marked ``@tool``.
27
+ mcp_path: Where to serve the MCP endpoint (``POST``).
28
+ utcp_path: Where to serve the UTCP manual (``GET``).
29
+
30
+ Returns:
31
+ ``app``, so the call can be chained.
32
+
33
+ Raises:
34
+ ValueError: If ``mode`` is not ``"all"`` or ``"opt-in"``.
35
+
36
+ Example:
37
+ ```python
38
+ from fastbridge.fastapi import bridge
39
+ bridge(app)
40
+ ```
41
+ """
42
+ if mode not in ("all", "opt-in"):
43
+ raise ValueError("mode must be 'all' or 'opt-in'")
44
+ own = {mcp_path, utcp_path}
45
+
46
+ def tools():
47
+ return discover(app, mode=mode, exclude_paths=own)
48
+
49
+ async def utcp(request: Request):
50
+ return JSONResponse(utcp_manual(tools(), str(request.base_url)))
51
+
52
+ async def mcp(request: Request):
53
+ if not is_json_content_type(request.headers.get("content-type", "")):
54
+ return JSONResponse({"error": "Content-Type must be application/json"}, 415)
55
+ try:
56
+ msg = await request.json()
57
+ except ValueError:
58
+ return JSONResponse(
59
+ {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}, 400
60
+ )
61
+ fwd = {k: v for k, v in request.headers.items() if k in FORWARD_HEADERS}
62
+
63
+ async def call(tool, args):
64
+ return await invoke(app, tool, args, fwd)
65
+
66
+ reply = await mcp_handle(tools(), msg, call)
67
+ return Response(status_code=202) if reply is None else JSONResponse(reply)
68
+
69
+ app.router.routes.append(Route(utcp_path, utcp, methods=["GET"], include_in_schema=False))
70
+ app.router.routes.append(Route(mcp_path, mcp, methods=["POST"], include_in_schema=False))
71
+ return app
@@ -0,0 +1,102 @@
1
+ """Discover tools from a Starlette app. FastAPI is Starlette, so it uses this too;
2
+ when the app can produce an OpenAPI document we enrich the schemas from it."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import inspect
7
+ from collections.abc import Collection, Iterator
8
+
9
+ from starlette.routing import Mount, Route
10
+
11
+ from ..ir import Param, ToolSpec
12
+ from ..naming import slug
13
+ from ..openapi import from_openapi
14
+
15
+ _CONVERTOR_SCHEMA = {
16
+ "integer": {"type": "integer"}, # keyed by convertor class name minus "Convertor"
17
+ "float": {"type": "number"},
18
+ "uuid": {"type": "string", "format": "uuid"},
19
+ "path": {"type": "string"},
20
+ "string": {"type": "string"},
21
+ }
22
+ _BODY_METHODS = {"POST", "PUT", "PATCH"}
23
+ _SKIP_METHODS = {"HEAD", "OPTIONS"}
24
+
25
+
26
+ def _included_router_routes(route) -> list:
27
+ """Expand a FastAPI ``_IncludedRouter`` into its effective routes.
28
+
29
+ Recent FastAPI versions no longer flatten ``include_router`` into ``app.routes``;
30
+ they keep a lazy wrapper instead. ``iter_route_contexts`` is the function FastAPI
31
+ itself uses to expand it (for OpenAPI), and each context behaves like a route:
32
+ it has ``path_format``, ``endpoint``, ``methods`` and ``name``. Older versions
33
+ flatten routers and never produce the wrapper, so this is never reached there.
34
+ """
35
+ try:
36
+ from fastapi.routing import iter_route_contexts
37
+ except ImportError: # pragma: no cover - only without FastAPI, where no wrapper exists
38
+ return []
39
+ return list(iter_route_contexts([route]))
40
+
41
+
42
+ def _walk(routes, prefix: str = "") -> Iterator[tuple[str, Route]]:
43
+ for r in routes:
44
+ if type(r).__name__ == "_IncludedRouter":
45
+ for ctx in _included_router_routes(r):
46
+ if getattr(ctx, "path_format", None) is not None and getattr(ctx, "endpoint", None) is not None:
47
+ yield prefix + ctx.path_format, ctx
48
+ elif isinstance(r, Mount):
49
+ yield from _walk(getattr(r, "routes", []) or [], prefix + r.path)
50
+ elif isinstance(r, Route):
51
+ yield prefix + r.path_format, r # "{id:int}" -> "{id}"
52
+
53
+
54
+ def _from_starlette(route: Route, methods: str) -> tuple[list[Param], dict | None, bool]:
55
+ params = [
56
+ Param(
57
+ name,
58
+ "path",
59
+ dict(_CONVERTOR_SCHEMA.get(type(c).__name__.replace("Convertor", "").lower(), {"type": "string"})),
60
+ True,
61
+ )
62
+ for name, c in route.param_convertors.items()
63
+ ]
64
+ body = {"type": "object", "description": "JSON request body"} if methods in _BODY_METHODS else None
65
+ return params, body, False
66
+
67
+
68
+ def discover(app, *, mode: str = "all", exclude_paths: Collection[str] = ()) -> list[ToolSpec]:
69
+ spec = {}
70
+ if hasattr(app, "openapi"): # FastAPI
71
+ try:
72
+ spec = app.openapi()
73
+ except Exception: # broken schema must not break discovery
74
+ spec = {}
75
+ paths = spec.get("paths", {})
76
+ components = spec.get("components", {}).get("schemas", {})
77
+ skip = set(exclude_paths) | {
78
+ getattr(app, a, None) for a in ("openapi_url", "docs_url", "redoc_url", "swagger_ui_oauth2_redirect_url")
79
+ }
80
+
81
+ tools: list[ToolSpec] = []
82
+ seen: set[str] = set()
83
+ for path, route in _walk(app.routes):
84
+ if path in skip:
85
+ continue
86
+ endpoint = route.endpoint
87
+ target = getattr(endpoint, "__func__", endpoint)
88
+ if getattr(target, "__fastbridge_hidden__", False):
89
+ continue
90
+ if mode == "opt-in" and not getattr(target, "__fastbridge__", False):
91
+ continue
92
+ methods = sorted((route.methods or set()) - _SKIP_METHODS)
93
+ for method in methods:
94
+ op = paths.get(path, {}).get(method.lower())
95
+ params, body, req = from_openapi(op, components) if op else _from_starlette(route, method)
96
+ doc = (op or {}).get("description") or (op or {}).get("summary") or inspect.getdoc(target) or ""
97
+ name = route.name if len(methods) == 1 else f"{route.name}_{method.lower()}"
98
+ if not name or name in seen:
99
+ name = slug(method, path)
100
+ seen.add(name)
101
+ tools.append(ToolSpec(name, doc, method, path, params, body, req, free_query=op is None))
102
+ return tools
fastbridge/ir.py ADDED
@@ -0,0 +1,92 @@
1
+ """Framework-neutral tool description shared by every protocol output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class Param:
10
+ """One declared input of an endpoint.
11
+
12
+ Attributes:
13
+ name: Parameter name.
14
+ location: ``"path"``, ``"query"`` or ``"header"``.
15
+ schema: JSON Schema of the value.
16
+ required: Whether the caller must supply it.
17
+ """
18
+
19
+ name: str
20
+ location: str # "path" | "query" | "header"
21
+ schema: dict
22
+ required: bool = False
23
+
24
+
25
+ @dataclass
26
+ class ToolSpec:
27
+ """A framework-neutral description of one endpoint, shared by MCP and UTCP.
28
+
29
+ Each framework adapter produces these; the protocol layers consume them.
30
+
31
+ Attributes:
32
+ name: Tool name shown to the model.
33
+ description: Tool description, usually the endpoint docstring.
34
+ method: HTTP method.
35
+ path: Full path including any mounts, e.g. ``/items/{item_id}``.
36
+ params: Declared path, query and header inputs.
37
+ body: JSON Schema of the request body, if any.
38
+ body_required: Whether the body must be supplied.
39
+ free_query: The framework declares no query schema, so accept a
40
+ free-form ``query`` object.
41
+ utcp_callable: Whether a UTCP client could call the endpoint directly.
42
+ """
43
+
44
+ name: str
45
+ description: str
46
+ method: str
47
+ path: str # full path incl. mounts, e.g. "/items/{item_id}"
48
+ params: list[Param] = field(default_factory=list)
49
+ body: dict | None = None # JSON Schema of the request body, if any
50
+ body_required: bool = False
51
+ # No declared query schema (plain Starlette/Django): accept an optional free-form `query` object.
52
+ free_query: bool = False
53
+ # UTCP clients call the endpoint directly, not via our middleware.
54
+ # False when that would be rejected (e.g. Django CSRF).
55
+ utcp_callable: bool = True
56
+
57
+ # -- helpers -----------------------------------------------------------
58
+ @property
59
+ def body_is_flat(self) -> bool:
60
+ """Object bodies are merged into the top level of the tool input."""
61
+ return self.body is not None and self.body.get("type") == "object" and "properties" in self.body
62
+
63
+ def input_schema(self, *, flatten_body: bool = True, free_query: bool = True) -> dict:
64
+ """Build the JSON Schema for the tool's input.
65
+
66
+ Args:
67
+ flatten_body: Merge an object body's properties into the top level
68
+ (MCP). When ``False`` the body stays nested under ``body`` (UTCP,
69
+ which sends the body as a single field).
70
+ free_query: Include the free-form ``query`` object when the
71
+ framework declares no query schema.
72
+
73
+ Returns:
74
+ A JSON Schema object.
75
+ """
76
+ props = {p.name: p.schema for p in self.params}
77
+ required = [p.name for p in self.params if p.required]
78
+ if self.free_query and free_query:
79
+ props["query"] = {"type": "object", "description": "Query-string parameters", "additionalProperties": True}
80
+ if self.body:
81
+ if flatten_body and self.body_is_flat:
82
+ props.update(self.body["properties"])
83
+ if self.body_required:
84
+ required += self.body.get("required", [])
85
+ else:
86
+ props["body"] = self.body
87
+ if self.body_required:
88
+ required.append("body")
89
+ schema: dict = {"type": "object", "properties": props}
90
+ if required:
91
+ schema["required"] = required
92
+ return schema
@@ -0,0 +1,5 @@
1
+ """Litestar adapter: `from fastbridge.litestar import bridge`."""
2
+
3
+ from .bridge import bridge
4
+
5
+ __all__ = ["bridge"]
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import TypeVar
5
+
6
+ from litestar import Litestar, Request, Response, get, post
7
+
8
+ from ..executor import invoke
9
+ from ..protocols import FORWARD_HEADERS, is_json_content_type, mcp_handle, utcp_manual
10
+ from .discovery import discover
11
+
12
+ AppT = TypeVar("AppT", bound=Litestar)
13
+
14
+
15
+ def bridge(app: AppT, *, mode: str = "all", mcp_path: str = "/mcp", utcp_path: str = "/utcp") -> AppT:
16
+ """Add `/mcp` and `/utcp` to a Litestar app.
17
+
18
+ Discovery is lazy (it runs on every request), so endpoints registered after
19
+ this call are exposed too.
20
+
21
+ Args:
22
+ app: The application to bridge.
23
+ mode: ``"all"`` exposes every endpoint except those marked
24
+ ``@hidden``. ``"opt-in"`` exposes only endpoints marked ``@tool``.
25
+ mcp_path: Where to serve the MCP endpoint (``POST``).
26
+ utcp_path: Where to serve the UTCP manual (``GET``).
27
+
28
+ Returns:
29
+ ``app``, so the call can be chained.
30
+
31
+ Raises:
32
+ ValueError: If ``mode`` is not ``"all"`` or ``"opt-in"``.
33
+
34
+ Example:
35
+ ```python
36
+ from fastbridge.litestar import bridge
37
+ bridge(app)
38
+ ```
39
+ """
40
+ if mode not in ("all", "opt-in"):
41
+ raise ValueError("mode must be 'all' or 'opt-in'")
42
+ own = {mcp_path, utcp_path}
43
+
44
+ def tools():
45
+ return discover(app, mode=mode, exclude_paths=own)
46
+
47
+ @get(utcp_path, name="fastbridge_utcp", include_in_schema=False)
48
+ async def utcp(request: Request) -> Response:
49
+ return Response(utcp_manual(tools(), str(request.base_url)))
50
+
51
+ @post(mcp_path, name="fastbridge_mcp", include_in_schema=False, status_code=200)
52
+ async def mcp(request: Request) -> Response:
53
+ if not is_json_content_type(request.headers.get("content-type", "")):
54
+ return Response({"error": "Content-Type must be application/json"}, status_code=415)
55
+ try:
56
+ msg = json.loads(await request.body())
57
+ except ValueError:
58
+ return Response(
59
+ {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}, status_code=400
60
+ )
61
+ fwd = {k: v for k, v in request.headers.items() if k in FORWARD_HEADERS}
62
+
63
+ async def call(tool, args):
64
+ return await invoke(app, tool, args, fwd)
65
+
66
+ reply = await mcp_handle(tools(), msg, call)
67
+ return Response(None, status_code=202) if reply is None else Response(reply)
68
+
69
+ app.register(utcp)
70
+ app.register(mcp)
71
+ return app
@@ -0,0 +1,65 @@
1
+ """Discover tools from a Litestar app: walk the route handlers, enrich from its generated OpenAPI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Collection
7
+
8
+ from litestar.routes import HTTPRoute
9
+
10
+ from ..ir import Param, ToolSpec
11
+ from ..naming import slug
12
+ from ..openapi import from_openapi
13
+
14
+ _SKIP_METHODS = {"HEAD", "OPTIONS"}
15
+ _BODY_METHODS = {"POST", "PUT", "PATCH"}
16
+ _PY_TYPES = {int: "integer", float: "number"} # path parameter python type -> JSON Schema type
17
+
18
+
19
+ def _openapi(app) -> dict:
20
+ try:
21
+ return app.openapi_schema.to_schema()
22
+ except Exception: # openapi disabled or broken: fall back to route inference
23
+ return {}
24
+
25
+
26
+ def discover(app, *, mode: str = "all", exclude_paths: Collection[str] = ()) -> list[ToolSpec]:
27
+ spec = _openapi(app)
28
+ paths = spec.get("paths", {})
29
+ components = spec.get("components", {}).get("schemas", {})
30
+
31
+ tools: list[ToolSpec] = []
32
+ seen: set[str] = set()
33
+ for route in app.routes:
34
+ if not isinstance(route, HTTPRoute) or route.path_format in exclude_paths:
35
+ continue
36
+ for raw_method, (handler, _) in route.route_handler_map.items():
37
+ method = str(getattr(raw_method, "value", raw_method)).upper()
38
+ fn = handler.fn
39
+ if method in _SKIP_METHODS:
40
+ continue
41
+ if getattr(fn, "__module__", "").startswith("litestar."): # Litestar's own handlers (/schema, static)
42
+ continue
43
+ if getattr(fn, "__fastbridge_hidden__", False):
44
+ continue
45
+ if mode == "opt-in" and not getattr(fn, "__fastbridge__", False):
46
+ continue
47
+
48
+ op = paths.get(route.path_format, {}).get(method.lower())
49
+ if op:
50
+ params, body, req = from_openapi(op, components)
51
+ doc = op.get("description") or inspect.getdoc(fn) or ""
52
+ else:
53
+ params = [
54
+ Param(p.name, "path", {"type": _PY_TYPES.get(p.type, "string")}, True)
55
+ for p in route.path_parameters.values()
56
+ ]
57
+ body = {"type": "object", "description": "JSON request body"} if method in _BODY_METHODS else None
58
+ req, doc = False, inspect.getdoc(fn) or ""
59
+
60
+ name = handler.handler_name
61
+ if not name or name in seen:
62
+ name = slug(method, route.path_format)
63
+ seen.add(name)
64
+ tools.append(ToolSpec(name, doc, method, route.path_format, params, body, req, free_query=op is None))
65
+ return tools
fastbridge/naming.py ADDED
@@ -0,0 +1,6 @@
1
+ import re
2
+
3
+
4
+ def slug(method: str, path: str) -> str:
5
+ """Fallback tool name, e.g. get_items_item_id."""
6
+ return re.sub(r"\W+", "_", f"{method.lower()}_{path}").strip("_")
fastbridge/openapi.py ADDED
@@ -0,0 +1,35 @@
1
+ """Turn an OpenAPI operation into our IR. Shared by every framework that can emit OpenAPI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .ir import Param
6
+
7
+
8
+ def resolve(node, components: dict, depth: int = 0):
9
+ """Inline #/components/schemas refs (depth-limited to survive recursive models)."""
10
+ if isinstance(node, list):
11
+ return [resolve(n, components, depth) for n in node]
12
+ if not isinstance(node, dict):
13
+ return node
14
+ ref = node.get("$ref")
15
+ if ref and depth < 6:
16
+ target = components.get(ref.rsplit("/", 1)[-1])
17
+ if target is not None:
18
+ return resolve(target, components, depth + 1)
19
+ return {k: resolve(v, components, depth) for k, v in node.items() if k != "$ref" or depth >= 6}
20
+
21
+
22
+ def from_openapi(op: dict, components: dict) -> tuple[list[Param], dict | None, bool]:
23
+ """-> (params, body schema, body required)."""
24
+ params = [
25
+ Param(p["name"], p["in"], resolve(p.get("schema", {}), components), p.get("required", False))
26
+ for p in op.get("parameters", [])
27
+ if p["in"] in ("path", "query", "header")
28
+ ]
29
+ body, required = None, False
30
+ rb = op.get("requestBody")
31
+ if rb:
32
+ schema = rb.get("content", {}).get("application/json", {}).get("schema")
33
+ if schema is not None:
34
+ body, required = resolve(schema, components), rb.get("required", False)
35
+ return params, body, required
@@ -0,0 +1,118 @@
1
+ """UTCP manual and a minimal stateless MCP (Streamable HTTP, JSON responses)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Awaitable, Callable
7
+ from typing import Any
8
+
9
+ from . import __version__
10
+ from .executor import ToolError
11
+ from .ir import ToolSpec
12
+
13
+ MCP_VERSION = "2025-06-18"
14
+ # Headers copied from the MCP request onto the tool's internal request.
15
+ FORWARD_HEADERS = ("authorization", "cookie", "x-api-key")
16
+
17
+
18
+ def is_json_content_type(value: str) -> bool:
19
+ """Requiring application/json forces a CORS preflight, so other sites can't drive /mcp with a victim's cookies."""
20
+ return value.split(";")[0].strip().lower() == "application/json"
21
+
22
+
23
+ # ---------------------------------------------------------------- UTCP ----
24
+ def utcp_manual(tools: list[ToolSpec], base_url: str) -> dict:
25
+ """Build the UTCP manual served at ``/utcp``.
26
+
27
+ Tools that a UTCP client could not call directly (``utcp_callable`` is
28
+ false) are left out; they stay available over MCP.
29
+
30
+ Args:
31
+ tools: The discovered tools.
32
+ base_url: Public base URL of the app, used to build each tool's URL.
33
+
34
+ Returns:
35
+ The manual as a JSON-serialisable dict.
36
+ """
37
+ base = base_url.rstrip("/")
38
+ out = []
39
+ for t in tools:
40
+ if not t.utcp_callable:
41
+ continue
42
+ template = {"call_template_type": "http", "http_method": t.method, "url": base + t.path}
43
+ if t.body:
44
+ template["body_field"] = "body"
45
+ out.append(
46
+ {
47
+ "name": t.name,
48
+ "description": t.description,
49
+ # UTCP sends the body as one field, so keep it nested here (no flattening).
50
+ "inputs": t.input_schema(flatten_body=False, free_query=False),
51
+ "tool_call_template": template,
52
+ }
53
+ )
54
+ return {"utcp_version": "1.0.0", "manual_version": __version__, "tools": out}
55
+
56
+
57
+ # ----------------------------------------------------------------- MCP ----
58
+ def _err(id_, code, message):
59
+ return {"jsonrpc": "2.0", "id": id_, "error": {"code": code, "message": message}}
60
+
61
+
62
+ async def mcp_handle(tools: list[ToolSpec], msg: dict, call: Callable[[ToolSpec, dict], Awaitable[Any]]) -> dict | None:
63
+ """Handle one MCP JSON-RPC message.
64
+
65
+ Supports ``initialize``, ``ping``, ``tools/list`` and ``tools/call``.
66
+
67
+ Args:
68
+ tools: The discovered tools.
69
+ msg: The decoded JSON-RPC request.
70
+ call: Async ``call(tool, args)`` supplied by the framework adapter. It
71
+ returns the endpoint's decoded response and raises
72
+ :class:`~fastbridge.executor.ToolError` on an HTTP error.
73
+
74
+ Returns:
75
+ The JSON-RPC response, or ``None`` for a notification.
76
+ """
77
+ if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0" or "method" not in msg:
78
+ return _err(msg.get("id") if isinstance(msg, dict) else None, -32600, "Invalid Request")
79
+ method, id_, params = msg["method"], msg.get("id"), msg.get("params") or {}
80
+ if id_ is None: # notification
81
+ return None
82
+ if method == "initialize":
83
+ return {
84
+ "jsonrpc": "2.0",
85
+ "id": id_,
86
+ "result": {
87
+ "protocolVersion": params.get("protocolVersion", MCP_VERSION),
88
+ "capabilities": {"tools": {"listChanged": False}},
89
+ "serverInfo": {"name": "fastbridge", "version": __version__},
90
+ },
91
+ }
92
+ if method == "ping":
93
+ return {"jsonrpc": "2.0", "id": id_, "result": {}}
94
+ if method == "tools/list":
95
+ return {
96
+ "jsonrpc": "2.0",
97
+ "id": id_,
98
+ "result": {
99
+ "tools": [
100
+ {"name": t.name, "description": t.description, "inputSchema": t.input_schema()} for t in tools
101
+ ]
102
+ },
103
+ }
104
+ if method == "tools/call":
105
+ by_name = {t.name: t for t in tools}
106
+ tool = by_name.get(str(params.get("name")))
107
+ if tool is None:
108
+ return _err(id_, -32602, f"Unknown tool: {params.get('name')}")
109
+ try:
110
+ payload, is_error = await call(tool, params.get("arguments") or {}), False
111
+ except ToolError as e: # tool-level failure, not protocol failure
112
+ payload, is_error = {"status": e.status, "error": e.payload}, True
113
+ text = payload if isinstance(payload, str) else json.dumps(payload)
114
+ result = {"content": [{"type": "text", "text": text}], "isError": is_error}
115
+ if isinstance(payload, dict) and not is_error:
116
+ result["structuredContent"] = payload
117
+ return {"jsonrpc": "2.0", "id": id_, "result": result}
118
+ return _err(id_, -32601, f"Method not found: {method}")
fastbridge/py.typed ADDED
File without changes
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ihor Korolenko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,237 @@
1
+ Metadata-Version: 2.3
2
+ Name: fastbridge
3
+ Version: 0.1.0
4
+ Summary: Expose FastAPI, Starlette, Django and Litestar endpoints as MCP and UTCP tools with one line.
5
+ License: MIT
6
+ Keywords: mcp,utcp,model-context-protocol,llm,agents,tools,fastapi,starlette,django,litestar,openapi
7
+ Author: korolenkowork
8
+ Requires-Python: >=3.10
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Web Environment
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3 :: Only
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Provides-Extra: django
27
+ Provides-Extra: fastapi
28
+ Provides-Extra: litestar
29
+ Provides-Extra: starlette
30
+ Requires-Dist: django (>=4.2) ; extra == "django"
31
+ Requires-Dist: fastapi (>=0.110) ; extra == "fastapi"
32
+ Requires-Dist: httpx (>=0.27)
33
+ Requires-Dist: litestar (>=2.4) ; (python_version < "4.0") and (extra == "litestar")
34
+ Requires-Dist: starlette (>=0.36.3) ; extra == "starlette"
35
+ Project-URL: Changelog, https://github.com/korolenkowork/FastBridge/blob/main/CHANGELOG.md
36
+ Project-URL: Documentation, https://korolenkowork.github.io/FastBridge/
37
+ Project-URL: Homepage, https://github.com/korolenkowork/FastBridge
38
+ Project-URL: Issues, https://github.com/korolenkowork/FastBridge/issues
39
+ Project-URL: Repository, https://github.com/korolenkowork/FastBridge
40
+ Description-Content-Type: text/markdown
41
+
42
+ # FastBridge
43
+
44
+ [![PyPI](https://img.shields.io/pypi/v/fastbridge.svg)](https://pypi.org/project/fastbridge/)
45
+ [![Python versions](https://img.shields.io/pypi/pyversions/fastbridge.svg)](https://pypi.org/project/fastbridge/)
46
+ [![CI](https://github.com/korolenkowork/FastBridge/actions/workflows/ci.yml/badge.svg)](https://github.com/korolenkowork/FastBridge/actions/workflows/ci.yml)
47
+ [![Docs](https://github.com/korolenkowork/FastBridge/actions/workflows/docs.yml/badge.svg)](https://korolenkowork.github.io/FastBridge/)
48
+ [![License](https://img.shields.io/pypi/l/fastbridge.svg)](https://github.com/korolenkowork/FastBridge/blob/main/LICENSE)
49
+
50
+ Expose the endpoints you already have as **MCP** and **UTCP** tools, with one line
51
+ and no changes to the endpoints.
52
+
53
+ ```python
54
+ from fastapi import FastAPI
55
+ from fastbridge.fastapi import bridge
56
+
57
+ app = FastAPI()
58
+
59
+
60
+ @app.get("/items/{item_id}")
61
+ def get_item(item_id: int):
62
+ """Fetch one item by id."""
63
+ ...
64
+
65
+
66
+ bridge(app) # adds POST /mcp and GET /utcp
67
+ ```
68
+
69
+ Works with **FastAPI**, **Starlette**, **Django** and **Litestar**.
70
+
71
+ 📖 **Documentation: <https://korolenkowork.github.io/FastBridge/>**
72
+
73
+ ## Install
74
+
75
+ ```bash
76
+ pip install "fastbridge[fastapi]" # FastAPI
77
+ pip install "fastbridge[starlette]" # plain Starlette
78
+ pip install "fastbridge[django]" # Django
79
+ pip install "fastbridge[litestar]" # Litestar
80
+ ```
81
+
82
+ ```bash
83
+ poetry add "fastbridge[fastapi]"
84
+ uv add "fastbridge[fastapi]"
85
+ ```
86
+
87
+ Python 3.10 or newer. The core depends only on `httpx`; each framework is an
88
+ optional extra, so you only install the one you use.
89
+
90
+ ## What you get
91
+
92
+ | Endpoint | Protocol | What a client does |
93
+ |---|---|---|
94
+ | `GET /utcp` | [UTCP](https://utcp.io/) manual | Reads the manual, then calls your endpoints **directly** (no proxy). |
95
+ | `POST /mcp` | [MCP](https://modelcontextprotocol.io/) (Streamable HTTP, JSON-RPC) | `tools/list`, `tools/call`; calls run **inside your app**. |
96
+
97
+ ### UTCP view
98
+
99
+ ![UTCP manual](https://raw.githubusercontent.com/korolenkowork/FastBridge/main/docs/utcp.png)
100
+
101
+ ### MCP view
102
+
103
+ ![MCP server](https://raw.githubusercontent.com/korolenkowork/FastBridge/main/docs/mcp.png)
104
+
105
+ Both screenshots are real responses from
106
+ [`examples/fastapi_app.py`](https://github.com/korolenkowork/FastBridge/blob/main/examples/fastapi_app.py).
107
+
108
+ ## Usage
109
+
110
+ Each framework has its own subpackage; nothing framework-specific leaks into the others.
111
+
112
+ ```python
113
+ from fastbridge.fastapi import bridge # FastAPI and plain Starlette
114
+ from fastbridge.litestar import bridge # Litestar
115
+
116
+ bridge(app)
117
+ ```
118
+
119
+ ```python
120
+ # Django: settings.py. No view or URL changes.
121
+ INSTALLED_APPS = [..., "fastbridge.django"]
122
+ ```
123
+
124
+ ### Choosing what is exposed
125
+
126
+ By default (`mode="all"`) every endpoint becomes a tool. To expose only some,
127
+ use opt-in mode and the parameter-less `@tool` marker; `@hidden` removes an
128
+ endpoint in either mode.
129
+
130
+ ```python
131
+ from fastbridge import hidden, tool
132
+ from fastbridge.fastapi import bridge
133
+
134
+
135
+ @app.get("/items/{item_id}")
136
+ @tool # exposed in opt-in mode
137
+ def get_item(item_id: int): ...
138
+
139
+
140
+ @app.delete("/items/{item_id}")
141
+ @hidden # never exposed
142
+ def delete_item(item_id: int): ...
143
+
144
+
145
+ bridge(app, mode="opt-in")
146
+ ```
147
+
148
+ > **Think before leaving `mode="all"` on.** Every route, including `DELETE` and
149
+ > other state-changing routes, becomes callable by whoever can reach `/mcp`.
150
+ > Prefer `opt-in` for anything real.
151
+
152
+ ## How it works
153
+
154
+ Each adapter discovers your routes and describes them in one shared form, which
155
+ both protocols are generated from. A tool call is then a **real request through
156
+ your own app**, so middleware, dependencies, authentication and validation all
157
+ still run. `Authorization`, `Cookie` and `X-API-Key` are forwarded from the MCP
158
+ request. An endpoint that answers `4xx`/`5xx` becomes an MCP result with
159
+ `isError: true`, so the model sees what went wrong.
160
+
161
+ See [How it works](https://korolenkowork.github.io/FastBridge/how-it-works/) for
162
+ the details.
163
+
164
+ ## Framework coverage
165
+
166
+ | | FastAPI | Starlette | Litestar | Django |
167
+ |---|---|---|---|---|
168
+ | Input schema | full (OpenAPI) | path params only | full (OpenAPI) | path params only |
169
+ | Query params | declared | free-form `query` object | declared | free-form `query` object |
170
+ | Request body | declared | free-form `body` object | declared | free-form `body` object |
171
+
172
+ Where a framework declares no schema, MCP tools accept an optional free-form
173
+ `query` object and, for `POST`/`PUT`/`PATCH`, a free-form `body` object. UTCP
174
+ omits `query`, because its HTTP template cannot express an arbitrary query string.
175
+
176
+ ## Limits worth knowing
177
+
178
+ - **Django function views are assumed to be `GET`.** They do not declare their
179
+ methods, so a `@require_POST` view is listed as `GET`. Class-based views are
180
+ read properly.
181
+ - **Django and CSRF.** Tool calls over MCP skip CSRF checking. UTCP clients call
182
+ the view directly and would hit it, so CSRF-protected `POST` views are left out
183
+ of the UTCP manual (MCP only) unless they are `csrf_exempt`.
184
+ - **The MCP server is minimal:** stateless JSON responses. No sessions, SSE
185
+ streaming, resources or prompts.
186
+ - **`/mcp` and `/utcp` have no authentication of their own.** Anyone who can
187
+ reach them can list your tools; calls are then subject to each endpoint's
188
+ normal auth. See [Security](https://korolenkowork.github.io/FastBridge/security/).
189
+
190
+ ## Compatibility
191
+
192
+ | | Minimum | Newest tested |
193
+ |---|---|---|
194
+ | Python | 3.10 | 3.14 |
195
+ | Starlette | 0.36.3 | 1.10.0 |
196
+ | FastAPI | 0.110 | 0.165.0 |
197
+ | Django | 4.2 | 6.1.3 |
198
+ | Litestar | 2.4 | 2.25.0 |
199
+
200
+ CI runs the suite against the exact minimums and maximums on every change, and
201
+ against real MCP and UTCP clients. See
202
+ [Compatibility](https://korolenkowork.github.io/FastBridge/compatibility/).
203
+
204
+ ## Examples
205
+
206
+ ```bash
207
+ PYTHONPATH=src uvicorn fastapi_app:app --app-dir examples --port 8001
208
+ PYTHONPATH=src uvicorn django_app:application --app-dir examples --port 8002
209
+ PYTHONPATH=src uvicorn litestar_app:app --app-dir examples --port 8003
210
+ ```
211
+
212
+ Check a running server with the official clients (needs `mcp`, `utcp` and
213
+ `utcp-http` installed):
214
+
215
+ ```bash
216
+ python examples/verify_clients.py http://127.0.0.1:8001
217
+ ```
218
+
219
+ ## Development
220
+
221
+ ```bash
222
+ git clone https://github.com/korolenkowork/FastBridge
223
+ cd FastBridge
224
+ poetry install --with dev,docs
225
+ poetry run pytest
226
+ poetry run ruff check . && poetry run ruff format --check . && poetry run mypy
227
+ poetry run mkdocs serve
228
+ ```
229
+
230
+ To cut a release, see the header of
231
+ [`.github/workflows/publish.yml`](https://github.com/korolenkowork/FastBridge/blob/main/.github/workflows/publish.yml).
232
+ Changes are listed in the [changelog](https://github.com/korolenkowork/FastBridge/blob/main/CHANGELOG.md).
233
+
234
+ ## License
235
+
236
+ MIT. See [LICENSE](https://github.com/korolenkowork/FastBridge/blob/main/LICENSE).
237
+
@@ -0,0 +1,22 @@
1
+ fastbridge/__init__.py,sha256=w7W0-vU1TcwRrbVjmWa-slYUVeUcGtO3Dc9Mw00wXkg,410
2
+ fastbridge/decorators.py,sha256=wlvdF0ElyEs3gQbRygKERzXR9cof3R_KVdq1ZCbGZ-M,1290
3
+ fastbridge/django/__init__.py,sha256=bB0tkCPhlONAuwkUpgB1uF9lxolSmGfuBvyw-jNd2jE,91
4
+ fastbridge/django/apps.py,sha256=Q5GP0Br7gFRNSfh-hrnpgtK1T65s-BBVvTlMRvGNmLw,608
5
+ fastbridge/django/discovery.py,sha256=C9pnJ7Mekq12v0Gr2ZojVEgGLXngNiP514UceiQw-TE,4634
6
+ fastbridge/django/middleware.py,sha256=AYR-Hb7Gg3-bj_X46Rfn-S8G39lsBw3iw5GIsQ2EHss,4239
7
+ fastbridge/executor.py,sha256=9n0zVJdggs-gBE_ZC_Tw1sHmhl1tWQtg7qdvhm6jCv8,2257
8
+ fastbridge/fastapi/__init__.py,sha256=_6_e5M-pHxYiC1aL-dIi8hwucL_ksGIXxOtS1IHXvJM,152
9
+ fastbridge/fastapi/bridge.py,sha256=cUfl-Nzg5jGmNs-HOGkSdNiP89P3dC3zWuNnr_6zYkU,2587
10
+ fastbridge/fastapi/discovery.py,sha256=0RM00VbpvzE39lALJTm3d5llQ0bz1ctOcuKGf2X1tyI,4225
11
+ fastbridge/ir.py,sha256=xJgzU69hR5Sa-MTPTaslRVt3ktNeToKJoaTZuRDJFO0,3573
12
+ fastbridge/litestar/__init__.py,sha256=uLQ8mbQ22L_LuuDH9bOtDg_jjSw0lzQ_ENcKDpIB9yY,116
13
+ fastbridge/litestar/bridge.py,sha256=-zpbO5TiEEJOQpeM5hA7GmNxWvcEbjoBF2eS3M49omU,2497
14
+ fastbridge/litestar/discovery.py,sha256=t0VZRbJOd7x-MOu0hdwhXWXl5Ff6G9J15XDtgxdl7_c,2577
15
+ fastbridge/naming.py,sha256=W5vlWxc59_0tq061goyuz8D70ee0Dwy1L7Xh3GfWh1Q,177
16
+ fastbridge/openapi.py,sha256=PChoiXPcuWV9jl2-EW1218Kzz-Zs2E1a73faUppfOXY,1401
17
+ fastbridge/protocols.py,sha256=23yE2sylIC1OEgqmKc7tPuJzHBziRrPe6n4qm0NFRws,4695
18
+ fastbridge/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ fastbridge-0.1.0.dist-info/LICENSE,sha256=eY-1tZhAuf5yradBLzxfkhLvnobNHh1fimr2_qbQMFw,1071
20
+ fastbridge-0.1.0.dist-info/METADATA,sha256=cwOP1qHcsgiyPyJpKNXLiFyusQTb-3jWj3Rgjgcok-8,8587
21
+ fastbridge-0.1.0.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
22
+ fastbridge-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any