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.
Cos’è l’MCP?
Sezione intitolata “Cos’è l’MCP?”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
Utilizzo
Sezione intitolata “Utilizzo”Genera un Server MCP
Sezione intitolata “Genera un Server MCP”Puoi generare un server MCP Python in due modi:
- Installa il Nx Console VSCode Plugin se non l'hai già fatto
- Apri la console Nx in VSCode
- Clicca su
Generate (UI)
nella sezione "Common Nx Commands" - Cerca
@aws/nx-plugin - py#mcp-server
- Compila i parametri richiesti
- Clicca su
Generate
pnpm nx g @aws/nx-plugin:py#mcp-server
yarn nx g @aws/nx-plugin:py#mcp-server
npx nx g @aws/nx-plugin:py#mcp-server
bunx nx g @aws/nx-plugin:py#mcp-server
Puoi anche eseguire una prova per vedere quali file verrebbero modificati
pnpm nx g @aws/nx-plugin:py#mcp-server --dry-run
yarn nx g @aws/nx-plugin:py#mcp-server --dry-run
npx nx g @aws/nx-plugin:py#mcp-server --dry-run
bunx nx g @aws/nx-plugin:py#mcp-server --dry-run
Opzioni
Sezione intitolata “Opzioni”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 |
Output del Generatore
Sezione intitolata “Output del Generatore”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 aNone
)
- pyproject.toml Aggiornato con dipendenze MCP
- project.json Aggiornato con target di servizio del server MCP
Infrastruttura
Sezione intitolata “Infrastruttura”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
Directorypackages/common/terraform
Directorysrc
Directoryapp/ Moduli Terraform per l’infrastruttura specifica di un progetto/generatore
- …
Directorycore/ Moduli generici riutilizzati dai moduli in
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
Directorypackages/common/terraform/src
Directoryapp
Directorymcp-servers
Directory<project-name>
- <project-name>.tf Modulo per il deployment del tuo MCP Server
Directorycore
Directoryagent-core
- runtime.tf Modulo generico per il deployment su Bedrock AgentCore Runtime
Lavorare con il Tuo Server MCP
Sezione intitolata “Lavorare con il Tuo Server MCP”Aggiungere Strumenti
Sezione intitolata “Aggiungere Strumenti”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
Aggiungere Risorse
Sezione intitolata “Aggiungere Risorse”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}"
Configurazione con Assistanti AI
Sezione intitolata “Configurazione con Assistanti AI”File di configurazione
Sezione intitolata “File di configurazione”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" } } }}
Configurazione specifica dell’assistente
Sezione intitolata “Configurazione specifica dell’assistente”Consulta la seguente documentazione per configurare MCP con assistenti AI specifici:
Esecuzione del Server MCP
Sezione intitolata “Esecuzione del Server MCP”Inspector
Sezione intitolata “Inspector”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.
pnpm nx run your-project:your-server-name-inspect
yarn nx run your-project:your-server-name-inspect
npx nx run your-project:your-server-name-inspect
bunx 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
.
pnpm nx run your-project:your-server-name-serve-stdio
yarn nx run your-project:your-server-name-serve-stdio
npx nx run your-project:your-server-name-serve-stdio
bunx nx run your-project:your-server-name-serve-stdio
Questo comando usa uv run
per eseguire il server MCP con trasporto STDIO.
HTTP Streamable
Sezione intitolata “HTTP Streamable”Se vuoi eseguire il server MCP localmente usando il trasporto HTTP Streamable, puoi usare il target <your-server-name>-serve-http
.
pnpm nx run your-project:your-server-name-serve-http
yarn nx run your-project:your-server-name-serve-http
npx nx run your-project:your-server-name-serve-http
bunx 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”Infrastruttura come Codice
Sezione intitolata “Infrastruttura come Codice”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'); }}
Viene generato un modulo Terraform per il tuo progetto, denominato in base al name
scelto durante l’esecuzione del generatore, o <ProjectName>-mcp-server
per impostazione predefinita.
Puoi utilizzare questo modulo Terraform in un progetto Terraform:
# Server MCPmodule "my_project_mcp_server" { # Percorso relativo al modulo generato nel progetto common/terraform source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
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.
Autenticazione
Sezione intitolata “Autenticazione”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); }}
# Server MCPmodule "my_project_mcp_server" { # Percorso relativo al modulo generato nel progetto common/terraform source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
Per concedere l’accesso a richiamare l’agent, dovrai aggiungere una policy come la seguente, riferendoti all’output module.my_project_mcp_server.agent_core_runtime_arn
:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_mcp_server.agent_core_runtime_arn, "${module.my_project_mcp_server.agent_core_runtime_arn}/*" ]}
Autenticazione Cognito JWT
Sezione intitolata “Autenticazione Cognito JWT”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 configurare l’autenticazione JWT, puoi modificare il modulo del server MCP per configurare la variabile customJWTAuthorizer
come segue:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.name
# Sostituisci con i tuoi ID User Pool e Client o esponili come variabili user_pool_id = "xxx" user_pool_client_ids = ["yyy"]}
module "agent_core_runtime" { source = "../../../core/agent-core" agent_runtime_name = "MyProjectMcpServer" docker_image_tag = "my-scope-my-project-agent:latest" server_protocol = "MCP" customJWTAuthorizer = { discoveryUrl = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration", allowedClients = local.user_pool_client_ids } env = var.env additional_iam_policy_statements = var.additional_iam_policy_statements tags = var.tags}
Target Bundle e Docker
Sezione intitolata “Target Bundle e Docker”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
usandouv export
- Installa le dipendenze per la piattaforma target (
aarch64-manylinux2014
) usandouv 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 porta8000
, secondo il contratto di servizio MCP
Osservabilità
Sezione intitolata “Osservabilità”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à.