Salta ai contenuti

Server MCP Python

Genera un server Python per il Model Context Protocol (MCP) per fornire contesto ai Large Language Model (LLM), con opzione di deploy su Amazon Bedrock AgentCore.

Il Model Context Protocol (MCP) è uno standard aperto che permette agli assistenti AI di interagire con strumenti e risorse esterne. Fornisce un modo consistente per i LLM di:

  • Eseguire strumenti (funzioni) che compiono azioni o recuperano informazioni
  • Accedere a risorse che forniscono contesto o dati

Puoi generare un server MCP Python in due modi:

  1. Installa il Nx Console VSCode Plugin se non l'hai già fatto
  2. Apri la console Nx in VSCode
  3. Clicca su Generate (UI) nella sezione "Common Nx Commands"
  4. Cerca @aws/nx-plugin - py#mcp-server
  5. Compila i parametri richiesti
    • Clicca su Generate
    Parametro Tipo Predefinito Descrizione
    project Obbligatorio string - The project to add an MCP server to
    computeType string BedrockAgentCoreRuntime The type of compute to host your MCP server. Select None for no hosting.
    name string - The name of your MCP server (default: mcp-server)
    iacProvider string CDK The preferred IaC provider

    Il generatore aggiungerà questi file al tuo progetto Python esistente:

    • Directoryyour-project/
      • Directoryyour_module/
        • Directorymcp_server/ (o nome personalizzato se specificato)
          • __init__.py Inizializzazione pacchetto Python
          • server.py Definizione principale del server con strumenti e risorse di esempio
          • stdio.py Punto d’ingresso per trasporto STDIO, utile per server MCP locali semplici
          • http.py Punto d’ingresso per trasporto HTTP Streamable, utile per hosting del server MCP
          • Dockerfile Punto d’ingresso per hosting del server MCP (escluso se computeType è impostato a None)
      • pyproject.toml Aggiornato con dipendenze MCP
      • project.json Aggiornato con target di servizio del server MCP

    Poiché questo generatore fornisce infrastruttura come codice basata sul tuo iacProvider selezionato, creerà un progetto in packages/common che include i relativi costrutti CDK o moduli Terraform.

    Il progetto comune di infrastruttura come codice è strutturato come segue:

    • Directorypackages/common/constructs
      • Directorysrc
        • Directoryapp/ Construct per l’infrastruttura specifica di un progetto/generatore
        • Directorycore/ Construct generici riutilizzati dai construct in app
        • index.ts Punto di ingresso che esporta i construct da app
      • project.json Target di build e configurazione del progetto

    Per il deployment del tuo MCP Server, vengono generati i seguenti file:

    • Directorypackages/common/constructs/src
      • Directoryapp
        • Directorymcp-servers
          • Directory<project-name>
            • <project-name>.ts Costrutto CDK per il deployment del tuo MCP Server
            • Dockerfile File Docker passthrough utilizzato dal costrutto CDK
      • Directorycore
        • Directoryagent-core
          • runtime.ts Costrutto CDK generico per il deployment su Bedrock AgentCore Runtime

    Gli strumenti sono funzioni che l’assistente AI può chiamare per eseguire azioni. Il server MCP Python utilizza la libreria MCP Python SDK (FastMCP), che fornisce un approccio basato su decoratori per definire gli strumenti.

    Puoi aggiungere nuovi strumenti nel file server.py:

    @mcp.tool(description="Descrizione del tuo strumento")
    def your_tool_name(param1: str, param2: int) -> str:
    """Implementazione dello strumento con type hints"""
    # Logica dello strumento qui
    return f"Risultato: {param1} con {param2}"

    La libreria FastMCP gestisce automaticamente:

    • Validazione dei tipi basata sui type hint della funzione
    • Generazione dello schema JSON per il protocollo MCP
    • Gestione errori e formattazione delle risposte

    Le risorse forniscono contesto all’assistente AI. Puoi aggiungere risorse usando il decoratore @mcp.resource:

    @mcp.resource("example://static-resource", description="Esempio risorsa statica")
    def static_resource() -> str:
    """Restituisce contenuto statico"""
    return "Questo è contenuto statico che fornisce contesto all'AI"
    @mcp.resource("dynamic://resource/{item_id}", description="Esempio risorsa dinamica")
    def dynamic_resource(item_id: str) -> str:
    """Restituisce contenuto dinamico basato su parametri"""
    # Recupera dati basati su item_id
    data = fetch_data_for_item(item_id)
    return f"Contenuto dinamico per {item_id}: {data}"

    La maggior parte degli assistenti AI che supportano MCP utilizza un approccio di configurazione simile. Dovrai creare o aggiornare un file di configurazione con i dettagli del tuo server MCP:

    {
    "mcpServers": {
    "your-mcp-server": {
    "command": "uv",
    "args": [
    "run",
    "python",
    "-m",
    "my_module.mcp_server.stdio"
    ],
    "env": {
    "VIRTUAL_ENV": "/path/to/your/project/.venv"
    }
    }
    }
    }

    Consulta la seguente documentazione per configurare MCP con assistenti AI specifici:

    Il generatore configura un target chiamato <your-server-name>-inspect che avvia l’MCP Inspector con la configurazione per connettersi al tuo server MCP usando il trasporto STDIO.

    Terminal window
    pnpm nx run your-project:your-server-name-inspect

    Questo avvierà l’inspector su http://localhost:6274. Inizia cliccando sul pulsante “Connect”.

    Il modo più semplice per testare e usare un server MCP è utilizzare l’inspector o configurarlo con un assistente AI (come sopra).

    Puoi comunque eseguire il server con il trasporto STDIO direttamente usando il target <your-server-name>-serve-stdio.

    Terminal window
    pnpm nx run your-project:your-server-name-serve-stdio

    Questo comando usa uv run per eseguire il server MCP con trasporto STDIO.

    Se vuoi eseguire il server MCP localmente usando il trasporto HTTP Streamable, puoi usare il target <your-server-name>-serve-http.

    Terminal window
    pnpm nx run your-project:your-server-name-serve-http

    Questo comando usa uv run per eseguire il server MCP con trasporto HTTP, tipicamente sulla porta 8000.

    Deploy del Server MCP su Bedrock AgentCore Runtime

    Sezione intitolata “Deploy del Server MCP su Bedrock AgentCore Runtime”

    Se hai selezionato BedrockAgentCoreRuntime per computeType, viene generata l’infrastruttura CDK o Terraform corrispondente che puoi utilizzare per distribuire il tuo server MCP su Amazon Bedrock AgentCore Runtime.

    Viene generato un costrutto CDK per il tuo progetto, denominato in base al name scelto durante l’esecuzione del generatore, o <ProjectName>McpServer per impostazione predefinita.

    Puoi utilizzare questo costrutto CDK in un’applicazione CDK:

    import { MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Aggiungi il server MCP al tuo stack
    new MyProjectMcpServer(this, 'MyProjectMcpServer');
    }
    }

    Docker è necessario per costruire e distribuire il tuo server MCP. Assicurati di aver installato e avviato Docker per evitare errori come:

    ERROR: Cannot connect to the Docker daemon at unix://path/to/docker.sock.

    Per impostazione predefinita, il tuo server MCP sarà protetto tramite autenticazione IAM. Basta distribuirlo senza argomenti aggiuntivi:

    import { MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    new MyProjectMcpServer(this, 'MyProjectMcpServer');
    }
    }

    Puoi concedere l’accesso per richiamare il tuo MCP su Bedrock AgentCore Runtime utilizzando il metodo grantInvoke. Ad esempio, potresti voler consentire a un agent generato con il generatore py#strands-agent di chiamare il tuo server MCP:

    import { MyProjectAgent, MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    const agent = new MyProjectAgent(this, 'MyProjectAgent');
    const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
    mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime);
    }
    }

    Di seguito viene dimostrato come configurare l’autenticazione Cognito per il tuo agent.

    Per configurare l’autenticazione JWT, puoi passare la proprietà authorizerConfiguration al costrutto del server MCP. Ecco un esempio che configura un User Pool e Client Cognito per proteggere il server MCP:

    import { MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    const userPool = new UserPool(this, 'UserPool');
    const client = userPool.addClient('Client', {
    authFlows: {
    userPassword: true,
    },
    });
    new MyProjectMcpServer(this, 'MyProjectMcpServer', {
    authorizerConfiguration: {
    customJWTAuthorizer: {
    discoveryUrl: `https://cognito-idp.${Stack.of(userPool).region}.amazonaws.com/${userPool.userPoolId}/.well-known/openid-configuration`,
    allowedClients: [client.userPoolClientId],
    },
    },
    });
    }
    }

    Per costruire il tuo server MCP per Bedrock AgentCore Runtime, viene aggiunto un target bundle che:

    • Esporta le dipendenze Python in un file requirements.txt usando uv export
    • Installa le dipendenze per la piattaforma target (aarch64-manylinux2014) usando uv pip install

    Viene anche aggiunto un target docker specifico per il tuo server MCP che:

    • Costruisce un’immagine docker dal Dockerfile che esegue il server MCP sulla porta 8000, secondo il contratto di servizio MCP

    Il tuo server MCP viene configurato automaticamente con l’osservabilità utilizzando AWS Distro for Open Telemetry (ADOT), tramite la configurazione dell’auto-strumentazione nel tuo Dockerfile.

    Puoi trovare le tracce nella Console AWS CloudWatch selezionando “GenAI Observability” nel menu. Nota che affinché le tracce vengano popolate, dovrai abilitare Transaction Search.

    Per ulteriori dettagli, consulta la documentazione di AgentCore sull’osservabilità.