This notebook demonstrates how to build a ReAct (Reasoning and Acting) agent using Catena di Langhe e LangGraph that can interact with a Couchbase database. The key to this interaction is the Model Context Protocol (MCP), which allows the AI agent to seamlessly connect to and use Couchbase as a tool. Read more about LangChain’s ReAct agent qui.
Cos'è il Protocollo del contesto modello (MCP)?
Il Modello di protocollo di contesto (MCP) è uno standard aperto progettato per standardizzare il modo in cui gli assistenti e le applicazioni IA si connettono e interagiscono con le fonti dati esterne, gli strumenti e i sistemi. Considerate MCP come un adattatore universale che consente ai modelli IA di accedere senza problemi al contesto di cui hanno bisogno per produrre risposte più pertinenti, accurate e praticabili.
Obiettivi e caratteristiche principali di MCP:
- Comunicazione standardizzata: MCP fornisce una lingua e una struttura comuni per i modelli di intelligenza artificiale che comunicano con diversi sistemi backend, eliminando la necessità di numerose integrazioni personalizzate.
- Gestione del contesto migliorata: Consente di gestire in modo efficiente i limiti di contesto dei sistemi di intelligenza artificiale, consentendo loro di mantenere interazioni più lunghe e coerenti e di sfruttare i dati storici.
- Accesso sicuro ai dati: MCP enfatizza le connessioni sicure, consentendo agli sviluppatori di esporre i dati tramite i server MCP mantenendo il controllo sull’infrastruttura.
- Utilizzo degli strumenti e capacità operative: Consente alle LLM non solo di recuperare informazioni, ma anche di utilizzare strumenti esterni e di attivare azioni in altri sistemi.
- Interoperabilità: Favorisce un ecosistema in cui diversi strumenti, modelli e fonti di dati di intelligenza artificiale possono collaborare in modo più coerente.
MCP mira a ridurre gli silos di dati, facilitando l’integrazione dell’intelligenza artificiale con le applicazioni del mondo reale e i sistemi aziendali, con conseguente sviluppo di soluzioni IA più potenti e consapevoli del contesto.
Il MCP segue tipicamente un'architettura client-server:
- MCP Host/Clienti: Applications (like AI assistants, IDEs, or other AI-powered tools) that want to access data or capabilities. In this demo, this notebook, through LangChain, acts as an MCP client.
- Server MCP: Programmi leggeri che esporranno specifiche fonti di dati o strumenti (ad esempio, un database o un'API) tramite il standardizzato MCP.
server-couchbase-mcpIl progetto svolge questo ruolo per Couchbase.
Ottieni le credenziali per OpenAI
Per favore seguite le istruzioni per generare le credenziali di OpenAI.
Creare e implementare il cluster operativo del livello gratuito su Capella
Per iniziare a utilizzare Couchbase Capella, creare un account e usarlo per implementare un cluster operativo a livello gratuito e permanente. Questo account vi fornisce un ambiente in cui potete esplorare e imparare a conoscere Capella senza restrizioni di tempo.
Per saperne di più, seguite il link istruzioni.
Configurazione di Couchbase Capella
Quando si esegue Couchbase utilizzando Capella, Per poter utilizzare questo servizio, è necessario soddisfare i seguenti requisiti preliminari.
- Creare il credenziali del database per accedere al bucket richiesto (Lettura e Scrittura) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
- La tua account gratuita Capella include un account di prova per i viaggi, con documenti di esempio utilizzati per prenotazioni e per scopi di viaggio. Puoi trovare ulteriori informazioni qui.
Istruzioni per l'installazione
Prima di avviare questo notebook, assicurarsi che siano soddisfatti i seguenti requisiti preliminari:
-
Impostazione delle variabili di ambiente: Questo notebook carica la chiave API di OpenAI e altre variabili di ambiente dal file
.envfile. Include quanto segue:OPENAI_API_KEY=il vostro codice API di OpenAI qui CB_CONNECTION_STRING=la vostra stringa di connessione Couchbase CB_USERNAME=il tuo username su Couchbase CB_PASSWORD=la tua password per Couchbase CB_BUCKET_NAME=il vostro bucket di destinazione #, ad esempio travel-sampleAbbiamo già incluso un
.env.samplefile. Modificate il nome del file in.enve inserire le variabili di ambiente. -
Configurazione uv: uv è un pacchetto e un gestore di progetti in Python moderno e veloce. Usiamo uv per eseguire il server MCP. Installiamo uv da qui.
-
Biblioteche Python: Installa le librerie necessarie eseguendo la cella di codice riportata di seguito.
%pip install -q 'langchain==1.3.11' 'langgraph==1.2.8' 'langchain-openai==1.3.3' 'langchain-mcp-adapters==0.3.0' 'python-dotenv==1.2.2'
Nota: potrebbe essere necessario riavviare il kernel per utilizzare i pacchetti aggiornati.
Importare le librerie necessarie
Questa cella importa gli strumenti Python essenziali per il nostro progetto:
dotenv&os: For loading and using secret API keys and other settings from a.envfile.mcp(ClientSession, StdioServerParameters, stdio_client): For connecting this notebook (as a client) to the MCP server, which in turn talks to Couchbase.langchain_mcp_adapters.tools(load_mcp_tools): To make the Couchbase tools (exposed via MCP) usable by our LangChain AI agent.langchain.agents(create_agent): To easily build a “ReAct” AI agent that can think and use tools.langgraph.checkpoint.memory(InMemorySaver): To help the agent remember past parts of the conversation.langchain_openai(ChatOpenAI): To connect to and use OpenAI’s language models (like GPT-5).
Attivare questa cella rende tutti questi componenti pronti all'uso.
from dotenv import load_dotenv
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from langchain_openai import ChatOpenAI
load_dotenv()
Verità
Definizione della funzione di risposta alle domande
Questa cella definisce una funzione asincrona qna(agent) that we’ll use to interact with our ReAct agent.
- Prende ciò che è stato creato
agentecome argomento. config = {"configurable": {"thread_id": "1"}}: This configuration is important for LangGraph agents. It uses athread_idto maintain conversation state. Using the samethread_idacross multiple calls to the agent allows it to remember previous interactions in that “thread.”- The function then defines a series of example questions (
messaggio) which we want to ask the agent. The agent queries the Couchbase MCP to get travel related data, formats it and presents it to the user. - This function allows us to easily test the agent with multiple queries in sequence.
async def qna(agent):
config = {"configurable": {"thread_id": "1"}}
message = "Tell me about the database that you are connected to."
print(f"nn**Running:** {message}n")
result = await agent.ainvoke({"messages": message}, config)
print(result["messages"][-1].content)
print('-'*50)
message = "List out the top 5 hotels by the highest aggregate rating?"
print(f"nn**Running**: {message}n")
result = await agent.ainvoke({"messages": message}, config)
print(result["messages"][-1].content)
print('-'*50)
message = "Recommend me a flight and hotel from New York to San Francisco"
print(f"nn**Running**: {message}n")
result = await agent.ainvoke({"messages": message}, config)
print(result["messages"][-1].content)
print('-'*50)
message = "I'm going to the UK for 1 week. Recommend some great spots to visit for sightseeing. Also mention the respective prices of those places for adults and kids."
print(f"nn**Running**: {message}n")
result = await agent.ainvoke({"messages": message}, config)
print(result["messages"][-1].content)
print('-'*50)
message = "My budget is around 30 pounds a night. What will be the best hotel to stay in?"
print(f"nn**Running**: {message}n")
result = await agent.ainvoke({"messages": message}, config)
print(result["messages"][-1].content)
print('-'*50)
Definizione della Prompt System
Il prompt del sistema è un elemento cruciale delle istruzioni fornite al Large Language Model (LLM) che alimenta il nostro agente. Definisce il contesto, definisce la personalità, le capacità e i limiti dell’agente.
In questo sistema, la richiesta è:
- Vi spieghiamo I livelli di archiviazione dei dati di Couchbase (Cluster, Bucket, Scope, Collection, Document) per aiutare il LLM a comprendere come i dati sono organizzati.
- Facciamo specificamente presente all'agente che “I dati sono all’interno
inventarioambito, quindi utilizzare solo quel campo di applicazione.” Questo concentra l'attenzione dell'agente sulla parte pertinente delTravel-samplebase di dati. - Offriamo Linee guida per la generazione di query SQL++:
- “Qualsiasi query generata deve includere solo il nome della raccolta nella clausola FROM.”
- “Ogni campo, collezione, ambito o nome di bucket all’interno della query deve essere contenuto all’interno di backticks.”
- L'obiettivo generale è guidare l'LLM a utilizzare efficacemente gli strumenti MCP forniti (che saranno le operazioni di Couchbase) e a formulare query SQL++ corrette per il
inventarioambito.
Un prompt di sistema ben strutturato migliora significativamente le prestazioni e l’affidabilità dell’agente.
system_prompt = """Couchbase organizes data with the following hierarchy (from top to bottom):
1. Cluster: The overall container of all Couchbase data and services.
2. Bucket: A bucket is similar to a database in traditional systems. Each bucket contains multiple scopes. Example: "users", "analytics", "products"
3. Scope: A scope is a namespace within a bucket that groups collections. Scopes help isolate data for different microservices or tenants. Default scope name: _default
4. Collection: The equivalent of a table in relational databases. Collections store JSON documents. Default collection name: _default
5. Document: The atomic data unit (usually JSON) stored in a collection. Each document has a unique key within its collection.
IMPORTANT SQL++ Query Rules:
- Use the tools to read the database and answer questions based on this database
- The data is inside `inventory` scope, so use only that scope
- Use only the collection name in the FROM clause (e.g., FROM `hotel`)
- Collection names and top-level field names should be in backticks
- For nested fields, use dot notation WITHOUT backticks around each part
CORRECT: `hotel`.reviews[0].ratings.Overall
WRONG: `hotel`.`reviews`.`ratings`.`Overall`
- When accessing nested objects or arrays, use bracket notation or dot notation directly
Examples:
- hotel.reviews[0].author
- hotel.geo.lat
Hotel Document Structure:
- Top-level fields: name, city, country, state, address, description, price, type, id, vacancy, pets_ok etc.
- address: A string field containing the street address (e.g., "321 Castro St")
- city, country, state: Top-level string fields (e.g., city = "San Francisco", country = "United States")
- geo: Object with fields {lat, lon, accuracy}
- reviews: Array of review objects with ratings and content
- To filter by city or country: WHERE `city` = "San Francisco" OR WHERE `country` = "United States"
- Do NOT use "addresses" (plural) - the field is "address" (singular)
ARRAY Operations in SQL++:
- To aggregate data from arrays (like reviews), use UNNEST to flatten the array first
- CORRECT way to sum array values:
SELECT h.name, SUM(r.ratings.Overall) as total_rating
FROM `hotel` h
UNNEST h.reviews r
GROUP BY h.name
ORDER BY total_rating DESC
- WRONG ways (these will cause parser errors):
x SELECT name, SUM(ARRAY_SUM(ARRAY reviews[*].ratings.Overall FOR reviews IN...))
x SELECT name, ARRAY reviews[*].ratings.Overall FOR reviews...
x WHERE ANY a IN addresses SATISFIES... (wrong field name)
- Use UNNEST whenever you need to work with individual array elements in aggregations"""
Configuring the Language Model and MCP Server
This cell sets up two key components:
model = ChatOpenAI(model="gpt-5.2"): This line initializes the LLM we’ll be using. We’re choosinggpt-5.2from OpenAI.server_params = StdioServerParameters(...):- This configures how our Python script will start and communicate with the
server-couchbase-mcpapplication. command="uvx"eargs=["couchbase-mcp-server"]: This usesuvx(from theuvtool) to automatically fetch and run the publishedserver-couchbase-mcppackage. No need to clone the repository — the package is installed and executed on the fly.env={...}: This dictionary defines environment variables that will be passed to the MCP server process when it starts. These are crucial for the MCP server to connect to your Couchbase instance:
- This configures how our Python script will start and communicate with the
model = ChatOpenAI(model="gpt-5.2")
server_params = StdioServerParameters(
command="uvx",
args=["couchbase-mcp-server"],
env={
"CB_CONNECTION_STRING": os.getenv("CB_CONNECTION_STRING"),
"CB_USERNAME": os.getenv("CB_USERNAME"),
"CB_PASSWORD": os.getenv("CB_PASSWORD"),
"CB_BUCKET_NAME": os.getenv("CB_BUCKET_NAME")
}
)
Defining the Main Execution Logic
Il main function ties everything together to set up and run our agent:
- Start & Connect to MCP Server: It first starts the
server-couchbase-mcpprocess usingstdio_clientand establishes a communicationClientSessionwith it. - Initialize Session & Load Tools: The MCP
sessionis initialized. Then,load_mcp_toolsqueries the MCP server to get the available Couchbase tools and prepares them for LangChain. - Set Up Agent Memory:
InMemorySaveris created to allow the agent to remember conversation history. - Create ReAct Agent: Il
create_agentfunction builds our AI agent, providing it with the languagemodel, the Couchbasetools, oursystem_prompt, and thecheckpointfor memory. - Run Q&A: Finally, it calls the
qnafunction, passing the createdagenteto start the question-and-answer process with the database.
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
print("Initializing connection...")
await session.initialize()
# Get tools
print("Loading tools...")
tools = await load_mcp_tools(session)
# Create and run the agent
print("Creating agent...")
checkpoint = InMemorySaver()
agent = create_agent(
model,
tools,
system_prompt=system_prompt,
checkpointer=checkpoint
)
print("-"*25, "Starting Run", "-"*25)
await qna(agent)
Running the Agent
This final cell simply executes the await main() function.
When you run this cell:
- Il
server-couchbase-mcpprocess will be started in the background. - The Python script will connect to it as an MCP client.
- The LangChain ReAct agent will be initialized with the Couchbase tools exposed via MCP.
- L'agente tenterà quindi di rispondere alla serie di domande definite nel
qnaFunzione di:- Riflessione sulla questione.
- Determinare se è necessario un tool di Couchbase.
- Formulare una query SQL++ (se opportuno, basata sulla richiesta del sistema).
- Esecuzione dell'utilità (che invia la query al server MCP, che la esegue poi su Couchbase).
- L’utilizzo dei risultati dell’applicazione per generare una risposta in linguaggio naturale.
You will see the questions and the agent’s answers printed below. This demonstrates the end-to-end flow of a natural language query being translated into database actions and then into a user-friendly response, all orchestrated by the LangChain agent using MCP.
await main()
Initializing connection...
Loading tools...
Creating agent...
------------------------- Starting Run -------------------------
**Running:** Tell me about the database that you are connected to.
You’re connected to a **Couchbase** cluster running at:
- **Connection string:** `couchbase://localhost`
- **Auth user:** `Administrator`
- **Server status:** running
- **Access mode:** **read-only** (documents and queries are restricted to read-only)
## Buckets available
- `travel-sample` (the sample travel dataset)
## Scopes & collections in `travel-sample`
- **`inventory`** (this is the main dataset for travel domain data)
- `airline`
- `airport`
- `hotel`
- `landmark`
- `route`
- **Tenant sample scopes** (multi-tenant style)
- `tenant_agent_00`: `users`, `bookings`
- `tenant_agent_01`: `users`, `bookings`
- `tenant_agent_02`: `users`, `bookings`
- `tenant_agent_03`: `users`, `bookings`
- `tenant_agent_04`: `users`, `bookings`
- `_default`: `_default`
- `_system`: `_query`, `_mobile`
## What’s inside the `inventory` scope (high level)
These collections store JSON documents with a top-level `type` field matching the entity:
- **`hotel`** (~917 docs): hotels with fields like `name`, `address`, `city`, `country`, `price`, `pets_ok`, `vacancy`, `geo`, and an array of `reviews` (each with `ratings.Overall`, etc.).
- **`airport`** (~1000 docs): airports with `airportname`, `city`, `country`, `geo` (lat/lon/alt), timezone `tz`, etc.
- **`landmark`** (~1000 docs): points of interest with `name`, `activity`, `city`, `country`, `geo`, and optional `address`, `hours`, `price`, etc.
- **`route`** (~1000 docs): flight routes with `sourceairport`, `destinationairport`, `airline`, `distance`, and an array `schedule`.
- **`airline`** (~187 docs): airlines with `name`, `country`, `icao`, and optional `iata`/`callsign`.
If you tell me what you’re trying to do (explore counts, example documents, common queries, indexes, etc.), I can pull specific details from the `inventory` collections.
--------------------------------------------------
**Running**: List out the top 5 hotels by the highest aggregate rating?
Top 5 hotels by **highest aggregate (sum) of `reviews[].ratings.Overall`**:
| Rank | Hotel | Total overall rating (sum) | Review count |
|---:|---|---:|---:|
| 1 | Hotel Eldorado | 109 | 29 |
| 2 | Hafod Lon Holiday Apartment | 70 | 17 |
| 3 | Uist Outdoor Centre | 53 | 12 |
| 4 | Lochmaddy Hotel | 50 | 11 |
| 5 | Radisson Blu | 50 | 13 |
--------------------------------------------------
**Running**: Recommend me a flight and hotel from New York to San Francisco
Here’s one solid **flight + hotel** recommendation (using what’s in the `inventory` data).
## Flight (New York → San Francisco)
- **Route:** **EWR → SFO** (Newark Liberty → San Francisco Intl)
- **Stops:** **0 (nonstop)**
- **Airlines available on this nonstop route:** **United (UA)** or **Virgin America (VX)**
- **Approx. distance:** ~**4118 km**
- **Airports:**
- New York area: **EWR/JFK/LGA** (I found nonstop options from **EWR** and **JFK** to **SFO**)
- San Francisco: **SFO (San Francisco Intl)**
If you prefer **JFK → SFO**, nonstop airlines in the data include **AA, DL, UA, VX, AS, B6, US**.
## Hotel (San Francisco)
Top-rated (by average review overall rating) among hotels currently marked with **`vacancy` = true**:
- **Wharf Inn** — **2601 Mason St**, San Francisco, CA
- **Avg overall rating:** 5.0 (from 8 reviews)
- **Vacancy:** true
If you tell me your preferred NYC departure airport (JFK/LGA/EWR), travel dates, and whether you care about free breakfast/parking/pets, I can narrow it down further.
--------------------------------------------------
**Running**: I'm going to the UK for 1 week. Recommend some great spots to visit for sightseeing. Also mention the respective prices of those places for adults and kids.
Some great **UK sightseeing spots** from the database (all are landmarks in the **United Kingdom**). I’m including the **adult/kid prices where the stored `price` text provides them**; in a few cases the data only lists a single price or uses concessions/family tickets instead of “kids”.
### 1) Glasgow School of Art (Glasgow)
- **Why go:** iconic architecture/design (Charles Rennie Mackintosh)
- **Price (from data):** **£9.75 adults**, **£4.75 youth** (also £8 students/seniors)
- **Address:** 167 Renfrew St
### 2) Glasgow Science Centre (Glasgow)
- **Why go:** very strong hands-on museum for a 1-week trip, great with kids
- **Price (from data):** **£10.50 adults**, **£8.50 children/seniors**
- Extras listed: add **£2.50** for planetarium/IMAX (each), **£4.95** for the tower
- **Address:** 50 Pacific Quay
### 3) Housesteads (Hadrian’s Wall) (Northumberland)
- **Why go:** one of the best Roman sites on Hadrian’s Wall
- **Price (from data):** **£6.20 adults**, **£3.70 children** (concessions £5.60)
- **Address:** Haydon Bridge, NE47 6NN
### 4) Vindolanda (Northumberland)
- **Why go:** major Roman fort/archaeology site near Hadrian’s Wall
- **Price (from data):** **£10 adults**, **£5.50 children** (also mentions a joint ticket option)
- **Address:** (not provided in the data row)
### 5) Kelvingrove Art Gallery and Museum (Glasgow)
- **Why go:** top museum with huge variety (art, natural history, etc.)
- **Price (from data):** **Free** (so adults/kids: **£0 / £0**)
- **Address:** Argyle Street, West End
### 6) Pevensey Castle (Pevensey)
- **Why go:** atmospheric castle/fortifications; easy classic “England castle” stop
- **Price (from data):** **£5.00 adults**, **£3.00 children** (concessions £4.50)
- **Address:** Castle Road, Pevensey, BN24 5LE
### 7) Rievaulx Abbey (North Yorkshire)
- **Why go:** dramatic abbey ruins in a beautiful setting
- **Price (from data):** **£6.00 adults**, **£3.60 children** (concessions £5.40)
- **Address:** Rievaulx, YO62 5LB
If you tell me which cities you’ll base yourself in (e.g., **London + York**, or **Edinburgh + Highlands**, etc.), I can turn this into a tight **7-day route** with nearby landmarks and more entries that explicitly list adult/child pricing.
--------------------------------------------------
**Running**: My budget is around 30 pounds a night. What will be the best hotel to stay in?
With a ~**£30/night** budget, the best match I can see in the UK hotel data **that’s currently showing `vacancy = true`** is:
## Rooms Inn (Newcastle upon Tyne)
- **Price:** *“Double £30–85, breakfast extra”* (so £30/night is achievable depending on date/room)
- **Vacancy:** true
- **Address:** 40 West Parade, NE4 7LB, Newcastle upon Tyne
A couple of other ~£30 options exist in the data, but they’re either **not available** (`vacancy = false`) or are **priced per person** rather than per room/night:
- **The Wellington (London)** — “From £30” but `vacancy = false`
- **Holmefield Gardens B&B (Barrowford)** — “From £30 per person breakfast included” (`vacancy = true`)
If you tell me **which city in the UK** you’re staying in (London vs elsewhere) and whether **£30 is per room or per person**, I can refine to the best pick for your exact plan.
--------------------------------------------------