Skip to main content

One decorator. Two interfaces. Build FastAPI + MCP backends with a single source of truth.

Project description

Unified Nexus

Unified Nexus is a high-performance Python framework that bridges the gap between traditional REST APIs and the new world of LLM-native tools (MCP). Build product-grade backends where your web frontend and AI agents share the exact same logic, schemas, and execution paths — defined once.


The Problem

In a traditional stack, you define a FastAPI route, then manually re-wrap it as an MCP tool. Over time, these two definitions drift apart — different validation, different schemas, different behavior. This is Code Drift, and it silently breaks your AI integrations.

❌ Traditional Stack
├── routes/user.py       ← HTTP logic
├── mcp_tools/user.py    ← Copy-pasted MCP logic (already out of sync)
└── models/user.py       ← Shared? Maybe. Hopefully.
✅ Unified Nexus
└── main.py              ← One function. One decorator. Both interfaces. Always in sync.

Installation

pip install unified-nexus

Quick Start

from unified_nexus import UnifiedNexus
from pydantic import BaseModel, Field

nexus = UnifiedNexus("MyNexusAPI")

class UserRequest(BaseModel):
    user_id: int = Field(..., description="The unique ID of the user")

@nexus.universal_tool(path="/user-info")
def get_user(req: UserRequest):
    """
    Fetches user status and clearance level.
    This docstring is used by both Swagger UI and AI Agents automatically.
    """
    return {"id": req.user_id, "status": "Active", "tier": "Gold"}

app = nexus.finalize()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Run it:

python main.py
Interface URL
REST API Docs (Swagger) http://localhost:8000/docs
MCP SSE Endpoint http://localhost:8000/mcp
MCP Inspector npx -y @modelcontextprotocol/inspector http://localhost:8000/mcp

Core Features

Single Source of Truth

Define your function once. Unified Nexus simultaneously registers it as a FastAPI route and an MCP tool. Validation, schemas, and business logic are identical for HTTP clients and AI agents — no drift, no duplication.

Auto-Method Detection

Unified Nexus intelligently selects GET or POST based on your function signature. Functions with a Pydantic model input default to POST; pure query-based functions use GET. No configuration needed.

AI-Native Tool Descriptions

Your Python docstrings become rich, structured tool descriptions for MCP hosts like Claude, Cursor, and Copilot. Descriptive Field(description=...) annotations on your Pydantic models are passed directly to the LLM — helping it understand how to call your tools correctly.

Shared Middleware

Apply authentication, rate limiting, or logging once at the UnifiedNexus level. The same middleware protects both your HTTP API and your MCP interface — no configuration duplication.

LLM-Optimized Errors

When your tool raises a Python exception, Unified Nexus converts it into a structured natural-language hint that helps LLMs self-correct their tool calls — rather than returning a raw stack trace the model cannot act on.

Lifespan-Safe MCP Integration

The finalize() method correctly composes FastAPI and FastMCP lifespans, ensuring the MCP StreamableHTTPSessionManager task group is always initialized before requests arrive. No runtime errors, no manual wiring.


Architecture

Your Code (@universal_tool)
        │
        ▼
  UnifiedNexus.finalize()
     ┌──────┴──────┐
     │             │
  FastAPI        FastMCP
  /docs           /mcp
  REST           SSE/MCP
     │             │
     └──────┬──────┘
            │
      Single ASGI App
      (Uvicorn / any ASGI server)

Advanced Usage

Custom Path and Methods

@nexus.universal_tool(path="/search", methods=["GET"])
def search_items(query: str, limit: int = 10):
    """Search the item catalog. Returns a ranked list of results."""
    return {"results": [...], "total": 42}

Shared Auth Middleware

from unified_nexus.middleware import BearerAuthMiddleware

nexus = UnifiedNexus("SecureAPI")
nexus.add_middleware(BearerAuthMiddleware, token="your-secret-token")

Async Support

@nexus.universal_tool(path="/fetch-data")
async def fetch_external(resource_id: str):
    """Fetches data from an external source asynchronously."""
    async with httpx.AsyncClient() as client:
        response = await client.get(f"https://api.example.com/{resource_id}")
    return response.json()

Connecting AI Agents

Claude Desktop (claude_desktop_config.json)

{
  "mcpServers": {
    "my-nexus-api": {
      "url": "http://localhost:8000/mcp",
      "transport": "streamable-http"
    }
  }
}

Cursor / VS Code

Add http://localhost:8000/mcp as an MCP server in your editor's AI settings.

Verify with MCP Inspector

npx -y @modelcontextprotocol/inspector http://localhost:8000/mcp

Requirements

  • Python 3.11+
  • FastAPI
  • FastMCP
  • Uvicorn
  • Pydantic v2

Contributing

Contributions are welcome! Please open an issue to discuss proposed changes before submitting a PR.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

unified_nexus-0.1.0.tar.gz (20.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

unified_nexus-0.1.0-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file unified_nexus-0.1.0.tar.gz.

File metadata

  • Download URL: unified_nexus-0.1.0.tar.gz
  • Upload date:
  • Size: 20.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for unified_nexus-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d6b858c0cf84ecbb0dec93d372deb4f9fb74ce30674b2de7d789b8bb45024dfd
MD5 a56f013d7dccb7d4db79ffd2af0c2fd6
BLAKE2b-256 ee528e433be1d7ba5ca0d3ba62c583e5000dd779e66a8a28b11beaf6bcebda06

See more details on using hashes here.

Provenance

The following attestation bundles were made for unified_nexus-0.1.0.tar.gz:

Publisher: publish.yml on rajboopathiking/UnifiedNexus

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file unified_nexus-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: unified_nexus-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for unified_nexus-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8eaa161b66b452dea9f60907ebfdb4113ccf0eb45e53031c449b69460c7897f4
MD5 5bb58c1cab51985c3a600ff45db7cebf
BLAKE2b-256 f1a1d19627823a4446a7ff20423c3be390b2ee5100c1b5b3a8752baa2d1eff8f

See more details on using hashes here.

Provenance

The following attestation bundles were made for unified_nexus-0.1.0-py3-none-any.whl:

Publisher: publish.yml on rajboopathiking/UnifiedNexus

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page