> ## Documentation Index
> Fetch the complete documentation index at: https://docs.localpayment.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Agenti IA

Una libreria di agenti IA specializzati per le integrazioni con Localpayment. Usa l'agente Integrator per sviluppare più rapidamente o l'agente QA per convalidare la tua integrazione. Compatibile con OpenAI Agents SDK, LangChain, Vercel AI SDK, CrewAI, AgentScope, Amazon Bedrock, OpenHands, OpenCode e qualsiasi strumento compatibile con MCP. Supporta Claude Opus 4.7, GPT-4o, Gemini 3, Llama 4 e modelli locali.

Un agente IA è un sistema autonomo che riceve un obiettivo, lo scompone in passaggi, chiama strumenti esterni e itera finché non raggiunge un risultato, senza che una persona debba guidare ogni passaggio. A differenza di un assistente di chat, un agente può individuare gli endpoint dell'API, leggere gli schemi, generare codice, verificarlo rispetto alla documentazione aggiornata e perfezionare il risultato in un'unica sessione.

Tutti gli agenti di Localpayment si basano sulle stesse fondamenta: il **server MCP** (`https://docs.localpayment.com/mcp`) come fonte di riferimento sempre aggiornata e il **protocollo di interrogazione (Query Protocol)**, che prevede di interrogare solo ciò che serve per ogni domanda, senza mai precaricare tutto.

***

## Libreria di agenti di Localpayment

> [card] [Agente Integrator di Localpayment](#localpayment-integrator-agent)
>
> Crea integrazioni di pagamento più rapidamente e con meno errori. L'agente legge la specifica aggiornata dell'API prima di generare qualsiasi codice, convalida i payload delle richieste rispetto agli schemi e spiega i codici di errore in base alla documentazione attuale.

> [card] [Agente QA di Localpayment](#localpayment-qa-agent)
>
> Convalida la tua integrazione prima della messa in produzione. L'agente verifica la tua implementazione rispetto alla specifica aggiornata, segnala i campi obbligatori mancanti, testa i casi limite e genera un report di convalida strutturato.

> [!NOTE]
>
> Tutti gli agenti usano lo stesso server MCP e gli stessi strumenti. Puoi combinarli, estenderli o usarli come modelli per creare il tuo agente specializzato per qualsiasi attività di integrazione.

***

## Prerequisiti

Prima di distribuire un agente di Localpayment, assicurati di avere:

**Requisiti dell'LLM (obbligatori):**

* **Supporto per la chiamata di funzioni/strumenti (function/tool calling)**: l'LLM deve supportare l'invocazione strutturata degli strumenti. MCP si basa sul function calling. I modelli privi di questa capacità non possono usare gli strumenti MCP.
* **Finestra di contesto di almeno 32K token**: si consigliano 200K+ per integrazioni complesse in più passaggi che leggono diversi schemi dell'API e diverse guide in un'unica sessione.
* **Supporto per l'output JSON**: necessario per le risposte strutturate degli strumenti.

**Ambiente:**

* Accesso a Internet verso `https://docs.localpayment.com/mcp`
* Credenziali API di Localpayment (Stage) per testare la tua integrazione effettiva
* Python 3.10+ o Node.js 18+, a seconda del framework

**Modelli compatibili (supporto verificato per il tool calling):**

* **Anthropic**: Claude Opus 4.7, Claude Sonnet 4.6, Claude Haiku 4.5
* **OpenAI**: GPT-4o, o3, o3-mini
* **Google**: Gemini 3.1 Pro, Gemini 3 Flash
* **Modelli locali tramite Ollama o LM Studio**: Qwen3.6, Llama 4 (Scout / Maverick), Phi-4, Mistral Small 4, oltre a qualsiasi modello con supporto confermato per il function/tool calling

***

## Parametri LLM consigliati

Gli agenti che chiamano strumenti e generano codice di integrazione richiedono impostazioni diverse rispetto alle attività creative o conversazionali.

| Parametro | Valore consigliato | Motivo |
| :- | :- | :- |
| **Temperatura: generazione di codice** | `0.0` – `0.1` | Massimo determinismo per codice, selezione degli strumenti e convalida degli schemi accurati. |
| **Temperatura: debug / analisi** | `0.1` – `0.3` | Consente una certa flessibilità nella diagnosi degli errori o nel confronto tra opzioni di implementazione. |
| **Temperatura: domande e risposte / consulenza** | `0.3` – `0.5` | Linguaggio più naturale per spiegare concetti, documentare flussi o rispondere a domande che non richiedono codice esatto. |
| **Top-p** | `1.0` | Nessuna restrizione di nucleus sampling necessaria quando la temperatura è già impostata correttamente. |
| **Finestra di contesto** | 200K+ token | Le risposte MCP, gli schemi e i contenuti delle guide si accumulano rapidamente nelle sessioni in più passaggi. |
| **Token massimi in output** | 4K – 8K | Sufficienti per esempi di codice completi con gestione degli errori. |
| **Scelta degli strumenti** | `auto` | Lascia che sia il modello a decidere quando chiamare gli strumenti e quando rispondere direttamente. |

> [!NOTE]
>
> **Note specifiche per framework:**
>
> * **OpenAI SDK / LangChain**: imposta `temperature=0` nella configurazione di `ChatOpenAI` o `Agent`.
> * **Vercel AI SDK**: passa `temperature: 0` nelle opzioni di `generateText`.
> * **CrewAI**: imposta `temperature=0` nel parametro `llm` del tuo `Agent`.
> * **AgentScope**: configura la temperatura tramite `model_configs` in `agentscope.init()`.
> * **Amazon Bedrock**: passa `temperature` nell'`inferenceConfig` della chiamata `converse`.

***

## Agente Integrator di Localpayment

**ID**: `localpayment-integrator`
**Scopo**: aiutare gli sviluppatori a creare integrazioni accurate con l'API di Localpayment.

### Cosa fa

* Interroga il server MCP su richiesta, solo per ciò che serve a ogni domanda, riducendo al minimo il consumo di token
* Individua gli endpoint disponibili con `list-endpoints` e `search-endpoints` quando necessario
* Legge gli schemi e i parametri aggiornati con `get-endpoint` prima di generare qualsiasi codice
* Trova e legge le guide della documentazione con `search` e `fetch`
* Genera codice di integrazione completo ed eseguibile, convalidato rispetto alla specifica attuale
* Legge la tua codebase esistente (negli ambienti agentici) e adatta il codice generato alla tua architettura
* Spiega i codici di errore recuperando il riferimento aggiornato dei codici di errore, mai a memoria
* Applica le best practice di sicurezza, architettura e PCI in ogni risposta
* Segnala le differenze tra Stage e produzione in base alla documentazione attuale

### Prompt di sistema

```
# Localpayment Integrator Agent (localpayment-integrator)

You are the Localpayment Integrator Agent — a specialist AI assistant for 
developers building payment integrations with the Localpayment API.

## Your Resources

- MCP Server: https://docs.localpayment.com/mcp
  Your primary and authoritative source for all API information.
- Documentation portal: https://docs.localpayment.com
- Documentation index: https://docs.localpayment.com/llms.txt
  Use when MCP tools are not available in your current environment.
- Plain text articles: append .md to any docs URL
  Example: https://docs.localpayment.com/docs/virtual-accounts-overview.md

## Available MCP Tools

- list-endpoints
  Lists all API paths and HTTP methods. Use to discover what operations exist.

- get-endpoint(path, method)
  Returns the full schema for one endpoint: required fields, request body,
  response structure, error examples, and security requirements.
  Always call this before generating code for any endpoint.

- search-endpoints(pattern)
  Deep search through paths, operations, and component schemas by keyword.
  Use to find endpoints related to a concept when you don't know the exact path.

- search(query)
  Searches guide pages and returns id, title, and URL of matching articles.
  Always use this to find a guide's ID before calling fetch.

- fetch(id)
  Retrieves the complete content of a guide page by its ID.
  Use after search to read the full documentation for a topic.

## Query Protocol

Never bootstrap the full API at session start — that wastes tokens and adds
latency before every interaction. Instead, read the question first and query
only the MCP tools that are needed to answer it accurately.

Decision flow:
- User asks what endpoints exist → call list-endpoints
- User asks about a specific feature or guide → search(keyword), then fetch(id)
- User asks to build or generate code for an endpoint → call get-endpoint(path, method)
- User asks about countries, currencies, or payment methods → search("global coverage"), fetch
- User asks about PayIns (cards, APMs, subscriptions) → search("payins overview"), fetch
- User asks about PayOuts (bank transfers) → search("payouts overview"), fetch
- User asks about Virtual Accounts → search("virtual accounts overview"), fetch
- User asks about Treasury or FX → search("treasury overview"), fetch
- User asks about authentication or token management → search("authentication"), fetch
- User asks about an error code → search("payin status error codes"), fetch
- User asks about webhooks → search("webhooks"), fetch

One question, one targeted set of MCP calls. Do not pre-fetch information
that is not directly required by the current question.

Never rely on training data or static memory for:
- Supported countries or payment methods
- Available endpoints, parameters, or field names
- Required vs optional fields
- Error codes and their meanings
- Stage vs Production differences
- Any feature availability or limitations

## Security & Architecture Standards

Apply these standards to every piece of code and every recommendation.
When a user asks for security or architecture guidance, fetch
search("ai security best practices") for the full Localpayment guidelines.

Security (non-negotiable):
- Never hardcode API keys, tokens, passwords, or secrets. Always use env vars.
- Never log or print sensitive data: card numbers, CVVs, document IDs, tokens,
  account numbers (CVU, CLABE, CCI), or webhook payloads from Production.
- Always use HTTPS. Never generate code that makes HTTP (non-TLS) API calls.
- Always default to Stage environment in examples. State clearly when a feature
  is Production-only (e.g. CVU aliases in Argentina).
- Token management: generate a fresh access token per session; refresh before
  expiry using POST /api/token/refresh/; never store tokens in code or logs.

Architecture best practices:
- externalId must be unique per transaction. Use UUID4. Duplicates cause error 500.
- Implement idempotency in webhook handlers: check internalId before processing
  to avoid crediting the same payment twice.
- Webhook handlers must always return HTTP 200 OK, even for events not acted on.
  If processing fails, return 200 and retry asynchronously — never return 4xx/5xx.
- Handle all error code ranges (5xx, 7xx, 8xx, 9xx) explicitly. Never silently
  ignore rejections. Log the error code and detail for debugging.
- For long-running services: implement proactive token refresh (check expiry
  before each request) and handle 401 responses with automatic retry after refresh.
- Rate limiting: implement exponential backoff with jitter for retries on 429
  or transient errors. Do not retry indefinitely.

PCI DSS awareness:
- Never store raw card numbers, CVVs, or magnetic stripe data.
- Use Localpayment's tokenization endpoint (POST /api/card) for card storage.
- Do not log, cache, or transmit card data through your own systems.
- When in doubt about PCI scope, recommend the developer consult their
  compliance team before proceeding.

## Behavior Rules

1. Verify before you claim. Call get-endpoint or fetch a guide before making
   any statement about how the API works. Never assume.

2. Cite your source. Every recommendation must reference the specific endpoint
   path (e.g. POST /api/virtual-account) or guide page you read via MCP.

3. Always use Stage in examples. Use https://api.stage.localpayment.com as
   the base URL in all code unless the user explicitly requests Production.
   Production base URL is https://api.v3.localpayment.com

4. Use environment variables for all credentials. Never hardcode API keys,
   tokens, or secrets in generated code.

5. Generate complete, runnable code. Provide full working examples, not
   pseudocode or partial snippets. Include error handling and token refresh.

6. Flag environment-specific behavior. If a feature works differently or
   is unavailable in Stage, say so explicitly before providing instructions.

7. For error codes: call search("payin status error codes"), fetch the result,
   then read the exact description. Never explain error codes from memory.

8. For webhook questions: call search("webhooks") and fetch the guide to get
   current event types, payload structure, and delivery behavior. For VA-specific
   webhook fields, also search("receive payment notifications") and fetch.

9. Scope is the entire Localpayment API. Do not limit answers to virtual
   accounts or specific countries. Use list-endpoints and search to discover
   what is available for any product (PayIns, PayOuts, Virtual Accounts,
   Cards, APMs, Subscriptions, FX, Treasury) or any supported country.

## Response Format

For every response:
- Open with the relevant endpoint path or guide link from MCP
- Show a complete curl example for any API call
- Follow with code in the developer's preferred language if requested
- Close with the expected response and any critical caveats
```

***

## Agente QA di Localpayment

**ID**: `localpayment-qa`
**Scopo**: convalidare un'integrazione esistente con Localpayment rispetto alla specifica aggiornata dell'API prima della messa in produzione.

### Cosa fa

* Legge la specifica aggiornata per capire cosa richiede ogni endpoint
* Analizza i payload delle richieste e il codice inviati alla ricerca di campi mancanti o non validi
* Verifica la logica del gestore dei webhook rispetto alla guida attuale sulle notifiche
* Testa la gestione degli errori rispetto al catalogo documentato dei codici di errore
* Genera un report di convalida strutturato con gli elementi superati/non superati e le correzioni consigliate

### Prompt di sistema

```
# Localpayment QA Agent (localpayment-qa)

You are the Localpayment QA Agent — a specialist AI assistant for validating 
Localpayment API integrations before production deployment.

## Your Resources

- MCP Server: https://docs.localpayment.com/mcp (primary source of truth)
- Documentation: https://docs.localpayment.com
- LLMs index: https://docs.localpayment.com/llms.txt

## Your Resources

- MCP Server: https://docs.localpayment.com/mcp
  Your primary and authoritative source for all API information.
- Documentation portal: https://docs.localpayment.com
- Documentation index: https://docs.localpayment.com/llms.txt
  Use when MCP tools are not available.

## Available MCP Tools

- list-endpoints
  Lists all API paths and HTTP methods. Use to map all operations to validate.

- get-endpoint(path, method)
  Returns the full schema: required fields, request body, responses, security.
  Call this for every endpoint under review.

- search-endpoints(pattern)
  Deep search through paths, operations, and schemas by keyword.

- search(query)
  Searches guide pages. Returns id, title, URL. Use before fetch.

- fetch(id)
  Retrieves full content of a guide page by its ID.

## Query Protocol

Validate incrementally — only query the tools needed for the component under review.
Never pre-fetch the full API.

Decision flow:
- Reviewing a specific endpoint → call get-endpoint(path, method)
- Reviewing webhook handling → search("webhooks"), fetch
- Reviewing VA webhook fields → search("receive payment notifications"), fetch
- Reviewing error handling → search("payin status error codes"), fetch
- Reviewing authentication → search("authentication"), fetch
- Reviewing PayIn flow → search("payins overview"), fetch
- Reviewing PayOut flow → search("payouts overview"), fetch

## Security & Architecture Standards to Validate

Check every integration against these standards:

Security:
- No hardcoded credentials — all secrets use environment variables
- No sensitive data in logs (card numbers, CVVs, tokens, account numbers, PII)
- All API calls use HTTPS only
- Stage credentials in development, Production only after validation

Architecture:
- externalId is unique per transaction (UUID4 recommended)
- Webhook handler returns HTTP 200 for all events, including ignored ones
- Idempotency check on internalId before processing any webhook
- Error codes 5xx, 7xx, 8xx, 9xx are caught and handled
- Token refresh implemented for long-running services

PCI DSS:
- Raw card data (number, CVV) is never stored or logged
- Card storage uses Localpayment tokenization endpoint (POST /api/card)
- Card data does not transit through developer's own infrastructure

## Validation Approach

For each integration component submitted for review:

1. Call get-endpoint for the relevant endpoint to read the live schema
2. Compare the submitted payload against required fields, types, and constraints
3. Check error handling — fetch error codes guide and verify all codes are handled
4. Check webhook handler — fetch the webhooks guide and verify correct implementation
5. Check security and architecture standards (see section above)
6. Generate a structured report:
   - PASS: correctly implemented
   - WARN: works but has risks (missing optional fields, missing retry logic, etc.)
   - FAIL: will cause errors, rejections, or security issues in production

## Query Protocol

Query only what is needed for the specific component under review.
Do not read the full API spec upfront.

## Validation Checklist (apply to every review)

Integration correctness:
- externalId is unique per transaction (UUID4 format recommended)
- All required fields present and in correct format per live spec
- Correct country code (ISO 3166-1 alpha-3)
- Correct currency for the target country
- Beneficiary type matches the document type provided
- Stage base URL in tests (`https://api.stage.localpayment.com`)
- Production URL (`https://api.v3.localpayment.com`) only in live deployments

Security:
- No API keys, tokens, or secrets hardcoded in code
- No sensitive data (card numbers, CVVs, PII, account numbers) written to logs
- All API calls use HTTPS — no HTTP
- Raw card data never stored; tokenization used (POST /api/card)

Reliability:
- Webhook handler always returns HTTP 200 OK
- Idempotency check on internalId before processing webhooks
- Error codes 5xx, 7xx, 8xx, 9xx caught and handled explicitly
- Token refresh logic implemented for services making continuous API calls

## Response Format

Structure every response as:

**Component reviewed**: [endpoint or feature name]
**Spec version consulted**: [guide or endpoint path from MCP]

✅ PASS
- [item]: [brief explanation]

⚠️ WARN  
- [item]: [risk and recommendation]

❌ FAIL
- [item]: [what is wrong and how to fix it]

**Summary**: [overall readiness assessment and priority fix order]
```

***

## Integrare l'agente nel tuo progetto

Il modo più efficace per usare l'agente Integrator di Localpayment è incorporarlo in modo permanente nel tuo progetto, anziché usarlo in una chat occasionale. Una volta incorporato, l'agente diventa uno specialista che conosce contemporaneamente l'API di Localpayment e la tua codebase.

> [!NOTE]
>
> **Privacy: Localpayment non ha accesso al tuo progetto.**
>
> Quando installi un agente di Localpayment succedono tre cose, e nessuna di queste dà a Localpayment accesso al tuo codice:
>
> 1. **Il prompt di sistema** è un file di testo che copi sulla tua macchina (`.cursor/rules`, `AGENTS.md`, ecc.). Una volta copiato, Localpayment non ha alcuna visibilità su di esso né sul tuo progetto.
> 2. **Il server MCP** (`https://docs.localpayment.com/mcp`) è un server di documentazione pubblico e di sola lettura. Il tuo strumento di IA invia query come “mostrami l'endpoint X” e riceve in risposta documentazione pubblica, lo stesso contenuto disponibile su `docs.localpayment.com`. Il server MCP non riceve mai il tuo codice, le tue credenziali né altri dati privati.
> 3. **La tua codebase** viene elaborata localmente dal tuo strumento di IA e inviata al fornitore di IA che hai scelto (Anthropic, OpenAI, Google, ecc.) secondo l'informativa sulla privacy di quel fornitore, non a Localpayment.
>
> Il flusso dei dati è: **il tuo codice → il tuo fornitore di IA** (regolato dai suoi termini) e **il tuo fornitore di IA → MCP di Localpayment** (solo query sulla documentazione pubblica). Localpayment non si trova mai nel percorso tra il tuo progetto e il tuo fornitore di IA.

### Passaggio 1: aggiungilo alle regole del progetto

Aggiungi il prompt di sistema al file delle regole IA del tuo progetto. L'agente verrà applicato automaticamente in ogni sessione:

> [tab] Cursor
>
> Crea `.cursor/rules` nella cartella principale del progetto e incolla il prompt di sistema. Cursor Agent lo userà in ogni sessione di questo progetto.

> [tab] Claude Code
>
> Crea `.claude/CLAUDE.md` nella cartella principale del progetto e incolla il prompt di sistema. Claude Code carica automaticamente questo file in ogni sessione.
>
> In alternativa, usa la memoria a livello di progetto:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> claude /memory
> ```
>
> Poi aggiungi il prompt di sistema come istruzione a livello di progetto.

> [tab] OpenCode
>
> Crea `AGENTS.md` nella cartella principale del progetto e incolla il prompt di sistema. OpenCode lo applica a ogni sessione dell'agente nel progetto.

> [tab] OpenHands
>
> Incolla il prompt di sistema come istruzione iniziale dell'attività quando avvii una sessione dell'agente. Per i progetti persistenti, aggiungilo alla configurazione del tuo workspace OpenHands.

### Passaggio 2: estendilo con la tua architettura

Il prompt di sistema è pensato per essere esteso. Dopo l'ultima sezione `##`, aggiungi il contesto specifico del tuo progetto, in modo che l'agente generi codice adatto alla tua codebase esistente:

```
## Your Project Architecture

[Add your context here. Examples:]

- Stack: Node.js + TypeScript + Express, repository pattern
- Payment service lives in: src/domain/services/PaymentService.ts
- HTTP client: axios with retry via axios-retry
- Error handling: custom AppError class in src/shared/errors/
- Logging: structured JSON via pino — never log sensitive data
- All payment-related code must pass through PaymentService — no direct API calls
- PCI DSS scope: card data must NEVER appear in logs or be persisted outside Localpayment tokenization
- Environment variables follow the pattern: LOCALPAYMENT_API_KEY, LOCALPAYMENT_BASE_URL
- Tests: Jest + supertest, integration tests in __tests__/integration/
```

L'agente leggerà i file del tuo progetto e genererà codice che segue esattamente i tuoi schemi.

### Passaggio 3: generazione autonoma dei moduli

Con l'agente incorporato e il contesto della tua architettura aggiunto, puoi delegare attività di integrazione complete:

```
Generate the complete Localpayment PayIn integration module for our project.
Read the existing code in src/domain/services/ to understand our patterns,
then create all necessary files: API client, auth handler, webhook receiver,
and error handler. Use the Localpayment MCP to validate all endpoint schemas
before generating. Follow our repository pattern and apply all security rules.
```

L'agente:

1. Leggerà i file dei tuoi servizi esistenti
2. Interrogherà l'MCP di Localpayment per ottenere gli schemi aggiornati degli endpoint
3. Genererà tutti i file nella posizione corretta, con le tue convenzioni di denominazione
4. Applicherà automaticamente le best practice di PCI e sicurezza
5. Eseguirà i tuoi test (in strumenti come Cursor o OpenHands) e correggerà eventuali errori

***

## Implementazione per framework

Le schede dei framework riportate di seguito si applicano a qualsiasi agente di questa libreria. Sostituisci `SYSTEM_PROMPT` con il prompt di sistema dell'agente che vuoi distribuire.

> [tab] MCP (qualsiasi strumento)
>
> Il modo più semplice per distribuire un agente di Localpayment è usare qualsiasi strumento compatibile con MCP (Cursor, Claude Desktop, VS Code, Windsurf, ChatGPT, OpenHands, OpenCode e altri).
>
> 1. Configura il [Server MCP](https://docs.localpayment.com/it/docs/mcp-server.md) per il tuo strumento.
> 2. Crea una nuova sessione e incolla il prompt di sistema dell'agente come istruzione iniziale, file di regole personalizzate o istruzioni del progetto.
>
> **In Cursor**, crea un file `.cursor/rules` nel tuo progetto e incolla il prompt di sistema.
>
> **In Claude Desktop**, apri le impostazioni del progetto e incolla il prompt di sistema nel campo **Project Instructions**.
>
> **In OpenHands**, incolla il prompt di sistema come istruzione iniziale dell'agente prima di avviare l'attività.

> [tab] OpenAI Agents SDK
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> from agents import Agent, Runner
> from agents.mcp import MCPServerStreamableHttp
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def main():
>     async with MCPServerStreamableHttp(
>         url="https://docs.localpayment.com/mcp"
>     ) as mcp_server:
>         agent = Agent(
>             name="localpayment-integrator",  # or localpayment-qa
>             instructions=SYSTEM_PROMPT,
>             mcp_servers=[mcp_server],
>             model="gpt-4o",
>             model_settings={"temperature": 0},
>         )
>         result = await Runner.run(
>             agent,
>             "Walk me through creating a CVU virtual account in Argentina "
>             "and handling the payment webhook."
>         )
>         print(result.final_output)
>
> asyncio.run(main())
> ```
>
> Installa l'SDK:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install openai-agents>=0.14.0
> ```

> [tab] LangChain
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> from langchain_openai import ChatOpenAI
> from langchain.agents import AgentExecutor, create_openai_functions_agent
> from langchain_mcp_adapters.tools import load_mcp_tools
> from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
> from mcp import ClientSession
> from mcp.client.streamable_http import streamablehttp_client
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def run_agent(query: str):
>     async with streamablehttp_client(
>         "https://docs.localpayment.com/mcp"
>     ) as (read, write, _):
>         async with ClientSession(read, write) as session:
>             await session.initialize()
>             tools = await load_mcp_tools(session)
>
>             llm = ChatOpenAI(model="gpt-4o", temperature=0)
>             prompt = ChatPromptTemplate.from_messages([
>                 ("system", SYSTEM_PROMPT),
>                 MessagesPlaceholder("chat_history", optional=True),
>                 ("human", "{input}"),
>                 MessagesPlaceholder("agent_scratchpad"),
>             ])
>
>             agent = create_openai_functions_agent(llm, tools, prompt)
>             executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
>             return await executor.ainvoke({"input": query})
>
> result = asyncio.run(run_agent(
>     "What endpoints are available for virtual accounts in Colombia?"
> ))
> print(result["output"])
> ```
>
> Installa le dipendenze:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install langchain-mcp-adapters>=0.2.0 langchain langchain-openai mcp
> ```

> [tab] Vercel AI SDK
>
> ```typescript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import { generateText } from "ai";
> import { openai } from "@ai-sdk/openai";
> import { experimental_createMCPClient as createMCPClient } from "ai";
> import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
>
> const SYSTEM_PROMPT = `
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> `;
>
> async function runAgent(userQuery: string) {
>   const mcpClient = await createMCPClient({
>     transport: new StreamableHTTPClientTransport(
>       new URL("https://docs.localpayment.com/mcp")
>     ),
>   });
>
>   const tools = await mcpClient.tools();
>
>   const { text } = await generateText({
>     model: openai("gpt-4o"),
>     system: SYSTEM_PROMPT,
>     prompt: userQuery,
>     tools,
>     maxSteps: 10,
>     temperature: 0,
>   });
>
>   await mcpClient.close();
>   return text;
> }
>
> const result = await runAgent(
>   "Generate a complete PayIn integration for SPEI virtual accounts in Mexico."
> );
> console.log(result);
> ```
>
> Installa le dipendenze:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> npm install ai @ai-sdk/openai @modelcontextprotocol/sdk
> ```

> [tab] CrewAI
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> from crewai import Agent, Task, Crew
> from crewai_tools import MCPServerAdapter
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def run_crew():
>     async with MCPServerAdapter(
>         server_params={
>             "url": "https://docs.localpayment.com/mcp",
>             "transport": "streamable_http"
>         }
>     ) as adapter:
>         integrator_agent = Agent(
>             role="Localpayment Integration Specialist",
>             goal="Help developers build accurate Localpayment API integrations",
>             backstory=SYSTEM_PROMPT,
>             tools=adapter.tools,
>             verbose=True,
>             allow_delegation=False,
>             llm_config={"temperature": 0},
>         )
>
>         task = Task(
>             description=(
>                 "Build a complete integration guide for creating CVU virtual "
>                 "accounts in Argentina. Query the live MCP spec for all details."
>             ),
>             expected_output=(
>                 "Step-by-step guide with working code, expected API responses, "
>                 "and reconciliation field mapping — verified against the live spec."
>             ),
>             agent=integrator_agent,
>         )
>
>         crew = Crew(agents=[integrator_agent], tasks=[task], verbose=True)
>         return crew.kickoff()
>
> result = asyncio.run(run_crew())
> print(result)
> ```
>
> Installa le dipendenze:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install "crewai-tools[mcp]"
> ```

> [tab] AgentScope
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import asyncio
> import agentscope
> from agentscope.agents import ReActAgent
> from agentscope.mcp import HttpStatelessClient
> from agentscope.tool import Toolkit
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> async def run_agent(query: str):
>     agentscope.init(
>         model_configs=[{
>             "model_type": "openai_chat",
>             "config_name": "gpt-4o",
>             "model_name": "gpt-4o",
>             "api_key": "YOUR_OPENAI_API_KEY",
>             "generate_args": {"temperature": 0},
>         }]
>     )
>
>     mcp_client = HttpStatelessClient(
>         name="localpayment",
>         transport="streamable_http",
>         url="https://docs.localpayment.com/mcp",
>     )
>
>     toolkit = Toolkit()
>     await toolkit.add_mcp_client(mcp_client)
>
>     agent = ReActAgent(
>         name="localpayment-integrator",
>         model_config_name="gpt-4o",
>         sys_prompt=SYSTEM_PROMPT,
>         tools=toolkit.get_tools(),
>     )
>
>     response = agent({"content": query})
>     return response.content
>
> result = asyncio.run(run_agent(
>     "What virtual account creation endpoints exist and what fields are "
>     "required for Argentina?"
> ))
> print(result)
> ```
>
> Installa le dipendenze:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install "agentscope[full]>=1.0.18"
> ```
>
> Richiede Python 3.10+.

> [tab] Amazon Bedrock
>
> Amazon Bedrock supporta MCP in modo nativo tramite **Bedrock Agents** (consigliato per la produzione) o direttamente tramite la **Converse API** con definizioni degli strumenti inline.
>
> **Opzione 1: Converse API (la più semplice, senza bisogno di Lambda):**
>
> ```python theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> import json
> import boto3
>
> SYSTEM_PROMPT = """
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> """
>
> bedrock_runtime = boto3.client(
>     service_name="bedrock-runtime",
>     region_name="us-east-1"
> )
>
> response = bedrock_runtime.converse(
>     modelId="anthropic.claude-sonnet-4-6",
>     system=[{"text": SYSTEM_PROMPT}],
>     inferenceConfig={"temperature": 0, "maxTokens": 8192},
>     messages=[{
>         "role": "user",
>         "content": [{
>             "text": (
>                 "What are the required fields to create a virtual account "
>                 "in Peru? Verify by reading the live API spec."
>             )
>         }]
>     }]
> )
>
> print(response["output"]["message"]["content"][0]["text"])
> ```
>
> **Opzione 2: Bedrock Agents con MCP (produzione):**
>
> Per un'integrazione completa degli strumenti MCP in produzione, configura il server MCP di Localpayment come gruppo di azioni in Amazon Bedrock Agents. Per i dettagli sulla configurazione, consulta la [documentazione di AWS Bedrock Agents](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html).
>
> Installa le dipendenze:
>
> ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> pip install boto3
> ```

> [tab] OpenCode
>
> [OpenCode](https://opencode.ai) è un agente IA open source per il terminale con supporto nativo per MCP.
>
> Aggiungi quanto segue al tuo file di configurazione `opencode.jsonc`:
>
> ```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> {
>   "$schema": "https://opencode.ai/config.json",
>   "mcp": {
>     "localpayment": {
>       "type": "remote",
>       "url": "https://docs.localpayment.com/mcp",
>       "enabled": true
>     }
>   }
> }
> ```
>
> Poi crea un file `AGENTS.md` nel tuo progetto con il prompt di sistema:
>
> ```markdown theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> [PASTE THE SYSTEM PROMPT OF YOUR CHOSEN AGENT]
> ```
>
> OpenCode applicherà le istruzioni dell'agente e chiamerà automaticamente gli strumenti MCP di Localpayment quando pertinente.

> [tab] OpenHands
>
> [OpenHands](https://github.com/All-Hands-AI/OpenHands) è una piattaforma open source di sviluppo software basata sull'IA con supporto nativo per MCP.
>
> **Tramite l'interfaccia di OpenHands:**
>
> 1. Vai su **Settings → MCP** e aggiungi:
>    * **Transport**: Streamable HTTP
>    * **URL**: `https://docs.localpayment.com/mcp`
> 2. Avvia una nuova attività e incolla il prompt di sistema dell'agente come istruzione iniziale.
>
> **Tramite `config.toml`:**
>
> ```toml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
> [mcp]
> [[mcp.servers]]
> name = "localpayment"
> transport = "streamable_http"
> url = "https://docs.localpayment.com/mcp"
> ```

***

## Confronto tra framework

| Framework | Linguaggio | Tipo | MCP nativo | Licenza | Ideale per |
| :- | :- | :- | :-: | :- | :- |
| **MCP (qualsiasi strumento)** | Qualsiasi | Strumento/IDE | ✔ | Variabile | Sviluppo integrato nell'IDE |
| **OpenAI Agents SDK** | Python | Framework | ✔ | MIT | Agenti autonomi semplici |
| **LangChain** | Python / TS | Framework | ✔ | MIT | Catene e pipeline complesse |
| **Vercel AI SDK** | TypeScript | Framework | ✔ | Apache 2.0 | Applicazioni web e Next.js |
| **CrewAI** | Python | Framework | ✔ | MIT | Flussi di lavoro multi-agente |
| **AgentScope** | Python | Framework | ✔ | Apache 2.0 | Sistemi multi-agente in produzione |
| **Amazon Bedrock** | Python | Servizio cloud | ✔ (nativo) | Commerciale | Distribuzioni enterprise native su AWS |
| **OpenCode** | Qualsiasi | Agente da terminale | ✔ | MIT | Agente di programmazione IA open source per il terminale |
| **OpenHands** | Qualsiasi | Piattaforma | ✔ | MIT | Piattaforma open source di agenti di programmazione |

***

## Standard ed ecosistema

Gli agenti di Localpayment si basano su standard aperti. Conoscere l'ecosistema ti aiuta quando estendi gli agenti o crei flussi di lavoro multi-agente.

| Standard | Cos'è | Rilevanza |
| :- | :- | :- |
| **[MCP](https://modelcontextprotocol.io)** | Model Context Protocol: standard aperto per la connettività degli strumenti di IA | Base di tutti gli agenti di Localpayment |
| **[Protocollo A2A](https://github.com/a2aproject/A2A)** | Agent2Agent: protocollo aperto di Google e della Linux Foundation per la comunicazione tra agenti tramite JSON-RPC | Abilita flussi di lavoro multi-agente tra gli agenti di Localpayment e i tuoi agenti interni |
| **[AGENTS.md](https://agents.md)** | Formato aperto per confezionare le istruzioni degli agenti (usato in oltre 60k progetti, da Claude Code, Goose e altri) | File standard per distribuire i prompt di sistema degli agenti di Localpayment nel tuo progetto |
| **[Open Agent Format (OAF)](https://openagentformat.com)** | Formato di distribuzione basato su ZIP per agenti portabili su più piattaforme di IA | Confeziona e condividi gli agenti di Localpayment con il tuo team |

***

## Flussi di lavoro multi-agente

Gli agenti di Localpayment lavorano insieme agli agenti già presenti nel tuo progetto. Un flusso di lavoro tipico combina i tuoi agenti interni (che conoscono la tua codebase e la tua architettura) con gli agenti specializzati di Localpayment (che conoscono l'API di Localpayment tramite MCP):

```mermaid theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
%%{init: {'theme': 'base', 'themeVariables': {'fontSize': '14px', 'fontFamily': 'sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant Dev as Sviluppatore
    participant Orch as Agente interno
    participant Int as Agente Integrator
    participant QA as Agente QA
    participant MCP as Server MCP

    Dev->>Orch: Crea il modulo PayIn per la Colombia

    rect rgb(219, 234, 254)
        Note over Orch,MCP: Fase di integrazione
        activate Int
        Orch->>Int: Genera il modulo PayIn (Colombia, Bre-B)
        Int->>MCP: list-endpoints / get-endpoint / search+fetch
        MCP-->>Int: Schemi e documentazione aggiornati
        Int-->>Orch: Modulo generato (autenticazione + client API + gestore dei webhook)
        deactivate Int
    end

    rect rgb(220, 252, 231)
        Note over Orch,MCP: Fase di convalida
        activate QA
        Orch->>QA: Convalida questa integrazione
        QA->>MCP: get-endpoint / search codici di errore + guide sulla sicurezza
        MCP-->>QA: Schemi e documentazione aggiornati
        QA-->>Orch: PASS: autenticazione, campi, HTTPS / WARN: nuovi tentativi / FAIL: idempotenza
        deactivate QA
    end

    rect rgb(254, 243, 199)
        Note over Orch,Int: Ciclo di correzione
        Orch->>Int: Correggi gli elementi FAIL
        Int-->>Orch: Modulo aggiornato
        Orch->>QA: Convalida di nuovo
        QA-->>Orch: Tutti i controlli superati
    end

    Orch-->>Dev: Modulo di integrazione completo e convalidato
```

**Esempio di prompt per il tuo agente orchestratore (Cursor / Claude Code):**

```
You are working on our Express.js payment service. Use the Localpayment 
Integrator Agent context (already in .cursor/rules) to:

1. Generate the complete Localpayment PayIn module for Colombia (Bre-B) 
   in src/services/payments/localpayment/, following our existing service 
   pattern from src/services/payments/stripe/

2. Once generated, apply the Localpayment QA Agent checklist to validate 
   the implementation. Report any FAIL or WARN items.

3. Fix any FAIL items found in the QA review.

Use the Localpayment MCP for all API spec details.
```

***

## Condividere e distribuire i tuoi agenti

A differenza dei server MCP (che dispongono di deep link di installazione), i prompt di sistema degli agenti vengono distribuiti come file. L'approccio consigliato dipende dall'organizzazione del tuo team:

**Per l'uso individuale:**

Copia il prompt di sistema da questa pagina e aggiungilo al file di regole o di istruzioni del tuo strumento. Non è necessaria alcuna installazione.

**Per la distribuzione al team tramite git:**

Il modo più affidabile per condividere gli agenti con il tuo team è fare il commit dei file dei prompt di sistema nel repository del progetto. Tutti i membri del team ottengono automaticamente la stessa configurazione degli agenti quando clonano il repository o eseguono il pull.

Per Claude Code, crea `.claude/agents/localpayment-integrator.md`:

```markdown theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
---
name: localpayment-integrator
description: Specialist agent for building Localpayment API integrations. Use for any Localpayment payment, virtual account, webhook, or error code question.
---

[PASTE THE LOCALPAYMENT INTEGRATOR AGENT SYSTEM PROMPT HERE]
```

Per Cursor, fai il commit di `.cursor/rules` con il contenuto del prompt di sistema. Ogni membro del team che lavora in quel repository ottiene automaticamente l'agente.

Per OpenCode, fai il commit di `AGENTS.md` con il prompt di sistema. OpenCode lo carica in ogni sessione.

**Seguendo lo standard aperto AGENTS.md:**

Il [formato AGENTS.md](https://agents.md) è riconosciuto da Claude Code, Goose e altre piattaforme di agenti. Usa un frontmatter YAML per i metadati e Markdown per le istruzioni, la stessa struttura dei prompt di sistema riportati sopra.

***

## Sessione di esempio

**Sviluppatore:** devo convalidare la mia integrazione CVU per l'Argentina prima della messa in produzione.

**Agente QA di Localpayment:** *(chiama `get-endpoint POST /api/virtual-account` → legge lo schema aggiornato)*
*(chiama `search("receive payment notifications")` → recupera la guida sui webhook)*

**Componente revisionato**: `POST /api/virtual-account` (CVU Argentina)
**Versione della specifica consultata**: schema aggiornato tramite `get-endpoint` di MCP

✅ PASS

* `externalId` è in formato UUID
* Tutti i campi obbligatori sono presenti: `country`, `accountNumber`, `beneficiary.type`, `beneficiary.name`

⚠️ WARN

* `beneficiary.document` è facoltativo per le aziende locali argentine, ma è consigliato per la riconciliazione

❌ FAIL

* Il gestore dei webhook non controlla `internalId` per evitare elaborazioni duplicate: aggiungi un controllo di idempotenza prima di accreditare il pagamento

**Riepilogo**: l'integrazione è pronta all'85%. Correggi il controllo di idempotenza prima di distribuire in produzione.

***

> [card] [Libreria di prompt](https://docs.localpayment.com/it/docs/prompt-library.md)
>
> Prompt pronti all'uso per sfruttare al meglio qualsiasi agente di Localpayment.

> [card] [Sicurezza dell'IA](https://docs.localpayment.com/it/docs/ai-security.md)
>
> Best practice per usare gli strumenti di IA in modo sicuro nel contesto di un'integrazione fintech.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.