Skip to content

Commit eee87f1

Browse files
authored
Merge pull request #8 from kmjones1979/main
Update to add Vercel MCP experimental
2 parents f62a07e + a986bce commit eee87f1

File tree

4 files changed

+402
-107
lines changed

4 files changed

+402
-107
lines changed

agent/the-graph-agent-scaffold-eth/README.md

Lines changed: 257 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@
1818
- [Component Interaction](#component-interaction)
1919
- [Data Flow](#data-flow)
2020
- [Key System Features](#key-system-features)
21+
- [MCP Integration](#mcp-integration)
22+
- [Overview](#overview)
23+
- [Available MCP Tools](#available-mcp-tools)
24+
- [MCP Provider Implementation](#mcp-provider-implementation)
25+
- [MCP Usage Examples](#mcp-usage-examples)
2126
- [Available Subgraphs](#available-subgraphs)
2227
- [Adding New Subgraph Endpoints](#adding-new-subgraph-endpoints)
2328
- [Detailed Setup Guide](#detailed-setup-guide)
@@ -45,6 +50,7 @@
4550
-**Contract Hot Reload**: Your frontend auto-adapts to your smart contract as you edit it
4651
- 🤖 **AI-Powered Chat Interface**: Natural language interaction with blockchain data and smart contracts
4752
- 📊 **GraphQL Integration**: Query blockchain data through The Graph protocol
53+
- 🔌 **MCP Integration**: Direct connection to The Graph's official Model Context Protocol server
4854
- 🪝 **[Custom hooks](https://docs.scaffoldeth.io/hooks/)**: Collection of React hooks wrapper around [wagmi](https://wagmi.sh/)
4955
- 🧱 [**Components**](https://docs.scaffoldeth.io/components/): Collection of common web3 components
5056
- 🔥 **Burner Wallet & Local Faucet**: Quickly test your application
@@ -131,15 +137,24 @@ Detailed explanations of the foundational pieces of this application.
131137
- **Tool Definition**: Actions are described with a name, description, and a Zod schema for input validation, making them understandable and usable by the AI.
132138
- **Invocation**: The AI decides which tool to use based on the user's query and the provided descriptions. The `app/api/chat/route.ts` orchestrates this.
133139

134-
3. **GraphQL Integration** (`utils/chat/agentkit/action-providers/graph-querier.ts`)
140+
3. **MCP Integration** (`utils/chat/agentkit/action-providers/graph-mcp-provider.ts`)
135141

136-
- **Functionality**: Enables the AI agent to fetch data from The Graph Protocol by constructing and executing GraphQL queries.
142+
- **Functionality**: Connects directly to The Graph's official Model Context Protocol (MCP) server, providing advanced subgraph discovery and querying capabilities.
143+
- **Key Aspects**:
144+
- **Official MCP Server**: Connects to `https://subgraphs.mcp.thegraph.com/sse` using Server-Sent Events (SSE) transport.
145+
- **Dynamic Subgraph Discovery**: Search and discover subgraphs by keyword or contract address.
146+
- **Schema Introspection**: Retrieve GraphQL schemas for any subgraph to understand available entities and fields.
147+
- **Flexible Querying**: Execute GraphQL queries against subgraphs using subgraph ID, deployment ID, or IPFS hash.
148+
149+
4. **Legacy GraphQL Integration** (`utils/chat/agentkit/action-providers/graph-querier.ts`)
150+
151+
- **Functionality**: Static GraphQL integration with pre-configured subgraph endpoints (maintained for backward compatibility).
137152
- **Key Aspects**:
138153
- **Subgraph Endpoints**: Manages a list of pre-configured (and dynamically accessible via API key) subgraph URLs (e.g., Uniswap, Aave).
139154
- **Dynamic Queries**: The AI can request queries against any of the configured subgraphs.
140155
- **Type Safety**: Uses Zod schemas to validate the structure of GraphQL queries formulated by the agent.
141156

142-
4. **Token API Integration** (Proxy: `app/api/token-proxy/route.ts`, Utilities: `utils/chat/agentkit/token-api/utils.ts`, Schemas: `utils/chat/agentkit/token-api/schemas.ts`)
157+
5. **Token API Integration** (Proxy: `app/api/token-proxy/route.ts`, Utilities: `utils/chat/agentkit/token-api/utils.ts`, Schemas: `utils/chat/agentkit/token-api/schemas.ts`)
143158
- **Functionality**: Provides access to comprehensive token data (balances, transfers, metadata, market prices, etc.) from an external token API service (e.g., The Graph's Token API).
144159
- **Key Aspects**:
145160
- **Proxy Server**: A Next.js API route (`/api/token-proxy`) that securely forwards requests to the external token API. This is crucial for hiding API keys from the client-side.
@@ -150,7 +165,55 @@ Detailed explanations of the foundational pieces of this application.
150165

151166
This section highlights critical files and their roles within the application architecture.
152167

153-
1. **GraphQL Query Handler** (`utils/chat/agentkit/action-providers/graph-querier.ts`)
168+
1. **MCP Provider** (`utils/chat/agentkit/action-providers/graph-mcp-provider.ts`)
169+
170+
- **Purpose**: Implements an AgentKit `ActionProvider` that connects to The Graph's official MCP server for dynamic subgraph discovery and querying.
171+
- **Core Logic**:
172+
- Uses `experimental_createMCPClient` from Vercel AI SDK to establish SSE connection to `https://subgraphs.mcp.thegraph.com/sse`.
173+
- Provides memoized connection management to ensure single client instance.
174+
- Exposes five main actions: `searchSubgraphs`, `getContractSubgraphs`, `getSubgraphSchema`, `executeMCPQuery`, and `listMCPTools`.
175+
- Handles authentication using `GRAPH_API_KEY` as Bearer token.
176+
177+
```typescript
178+
// Core MCP client setup with memoization
179+
const getMcpClient = memoize(async () => {
180+
if (!process.env.GRAPH_API_KEY) {
181+
throw new Error("GRAPH_API_KEY environment variable not set.");
182+
}
183+
184+
const client = await experimental_createMCPClient({
185+
transport: {
186+
type: "sse",
187+
url: "https://subgraphs.mcp.thegraph.com/sse",
188+
headers: {
189+
Authorization: `Bearer ${process.env.GRAPH_API_KEY}`,
190+
},
191+
},
192+
});
193+
194+
return client;
195+
});
196+
197+
// Example action: Search for subgraphs by keyword
198+
{
199+
name: "searchSubgraphs",
200+
description: "Search for subgraphs by keyword using The Graph's MCP",
201+
schema: searchSubgraphsSchema,
202+
invoke: async ({ keyword }) => {
203+
const result = await invokeMcpTool("search_subgraphs_by_keyword", { keyword });
204+
return JSON.stringify(result, null, 2);
205+
}
206+
}
207+
```
208+
209+
**Key Features & Best Practices**:
210+
211+
- **Connection Management**: Uses memoization to ensure efficient connection reuse.
212+
- **Error Handling**: Comprehensive error handling with structured error responses.
213+
- **Type Safety**: Full Zod schema validation for all inputs and outputs.
214+
- **Debug Support**: Includes `listMCPTools` action for troubleshooting available MCP tools.
215+
216+
2. **Legacy GraphQL Query Handler** (`utils/chat/agentkit/action-providers/graph-querier.ts`)
154217

155218
- **Purpose**: Implements an AgentKit `ActionProvider` that allows the AI to query various subgraphs available through The Graph Protocol.
156219
- **Core Logic**:
@@ -230,7 +293,7 @@ This section highlights critical files and their roles within the application ar
230293
- Supports query variables for dynamic data fetching.
231294
- **Best Practice**: Ensure `GRAPH_API_KEY` is set in `.env.local`. When adding new subgraphs, define them clearly in `SUBGRAPH_ENDPOINTS`. Keep query descriptions for the AI clear and specific.
232295

233-
2. **Chat API Route** (`app/api/chat/route.ts`)
296+
3. **Chat API Route** (`app/api/chat/route.ts`)
234297

235298
- **Purpose**: The main backend endpoint that receives user messages from the chat interface, orchestrates the AI's response generation using AgentKit and OpenAI, and streams the response back.
236299
- **Core Logic**:
@@ -287,7 +350,7 @@ This section highlights critical files and their roles within the application ar
287350
- Provides real-time response streaming.
288351
- **Best Practice**: Craft clear and comprehensive system prompts. This is crucial for guiding the AI's behavior and ensuring it uses the available tools correctly. Regularly update the prompt as new tools or capabilities are added. Secure this endpoint appropriately.
289352

290-
3. **Chat Interface** (`app/chat/page.tsx`)
353+
4. **Chat Interface** (`app/chat/page.tsx`)
291354

292355
- **Purpose**: The frontend React component that renders the chat UI, handles user input, displays messages (both user's and AI's), and visualizes tool calls and results.
293356
- **Core Logic**:
@@ -371,7 +434,7 @@ This section highlights critical files and their roles within the application ar
371434
- Error state management and display.
372435
- **Best Practice**: Provide clear visual feedback to the user about the AI's status (e.g., "AI is thinking...", "AI is using tool X..."). Ensure the UI gracefully handles and displays errors returned from the backend or from tool executions.
373436

374-
4. **Token API Proxy Route** (`app/api/token-proxy/route.ts`)
437+
5. **Token API Proxy Route** (`app/api/token-proxy/route.ts`)
375438

376439
- **Purpose**: A backend API route that acts as a secure intermediary between your application (specifically, the AgentKit actions running on the server) and an external Token API. This is essential for protecting your Token API credentials.
377440
- **Core Logic**:
@@ -473,7 +536,7 @@ This section highlights critical files and their roles within the application ar
473536
- **Error Handling**: Propagates errors from the external API back to the caller.
474537
- **Clarity**: The `path` parameter should clearly map to the external API's own path structure. For example, if the external API endpoint is `https://token-api.thegraph.com/v1/tokens/mainnet/0xContract/transfers?limit=10`, then `path` would be `v1/tokens/mainnet/0xContract/transfers` and `limit=10` would be a forwarded query parameter.
475538

476-
5. **Token API Utilities** (`utils/chat/agentkit/token-api/utils.ts`)
539+
6. **Token API Utilities** (`utils/chat/agentkit/token-api/utils.ts`)
477540

478541
- **Purpose**: A collection of server-side TypeScript functions designed to be used by AgentKit actions. These functions abstract the details of making requests to the `/api/token-proxy` to fetch various types of token information.
479542
- **Core Logic**:
@@ -609,7 +672,7 @@ This section highlights critical files and their roles within the application ar
609672
- Uses Zod schemas defined in `schemas.ts` for request parameters and API responses. This ensures that AgentKit actions provide valid data and can reliably consume the results.
610673
- **Best Practice**: Each utility function should have a clear, single responsibility. Input parameters and output structures should be robustly typed and validated using Zod. Implement comprehensive error handling and logging.
611674

612-
6. **Token API Schemas** (`utils/chat/agentkit/token-api/schemas.ts`)
675+
7. **Token API Schemas** (`utils/chat/agentkit/token-api/schemas.ts`)
613676

614677
- **Purpose**: This file centralizes the Zod schema definitions for all data structures related to the Token API. This includes schemas for parameters taken by the utility functions (and thus by AgentKit actions) and for the expected shapes of API responses.
615678
- **Core Logic**:
@@ -730,11 +793,11 @@ This section highlights critical files and their roles within the application ar
730793
API Route (route.ts)
731794
Processes with OpenAI
732795
Initializes AgentKit
733-
GraphQL Handler (graph-querier.ts) OR Token API Utilities (token-api/utils.ts)
734-
↓ ↓ Calls Token API Proxy
735-
Executes queries (The Graph) Token API Proxy (token-proxy/route.ts)
736-
Queries External Token API
737-
Returns results Returns results
796+
MCP Provider (graph-mcp-provider.ts) OR Legacy GraphQL Handler OR Token API Utilities
797+
Calls Token API Proxy
798+
Connects to MCP Server (SSE) Direct subgraph queries Token API Proxy (token-proxy/route.ts)
799+
Uses official MCP tools ↓ (Static endpoints)Queries External Token API
800+
Returns structured data Returns resultsReturns results
738801
API Route
739802
Streams response
740803
Chat Interface
@@ -804,6 +867,174 @@ This section was previously named "Key Features" and has been renamed for clarit
804867
- API key management
805868
- Input sanitization
806869

870+
## MCP Integration
871+
872+
### Overview
873+
874+
The MCP (Model Context Protocol) integration provides a direct connection to The Graph's official MCP server, enabling dynamic subgraph discovery and advanced querying capabilities. This is the recommended approach for interacting with The Graph protocol, offering superior flexibility compared to static endpoint configurations.
875+
876+
**Key Advantages:**
877+
878+
- **Dynamic Discovery**: Search and discover subgraphs by keywords or contract addresses
879+
- **Schema Introspection**: Automatically retrieve GraphQL schemas for any subgraph
880+
- **Official Support**: Direct connection to The Graph's maintained MCP server
881+
- **Real-time Updates**: Access to the latest subgraph information and metadata
882+
883+
### Available MCP Tools
884+
885+
The MCP provider exposes the following tools through The Graph's official MCP server:
886+
887+
| Tool Name | Description | Parameters |
888+
| ---------------------- | -------------------------------------- | ------------------------------------------------------- |
889+
| `searchSubgraphs` | Search for subgraphs by keyword | `keyword: string` |
890+
| `getContractSubgraphs` | Find top subgraphs indexing a contract | `contractAddress: string, chain: string` |
891+
| `getSubgraphSchema` | Get GraphQL schema for a subgraph | `subgraphId \| deploymentId \| ipfsHash` |
892+
| `executeMCPQuery` | Execute GraphQL query against subgraph | `query: string, subgraphId \| deploymentId \| ipfsHash` |
893+
| `listMCPTools` | Debug: List all available MCP tools | None |
894+
895+
### MCP Provider Implementation
896+
897+
The `GraphMCPProvider` class implements the AgentKit `ActionProvider` interface and manages the connection to The Graph's MCP server:
898+
899+
```typescript
900+
// Connection establishment with authentication
901+
const client = await experimental_createMCPClient({
902+
transport: {
903+
type: "sse",
904+
url: "https://subgraphs.mcp.thegraph.com/sse",
905+
headers: {
906+
Authorization: `Bearer ${process.env.GRAPH_API_KEY}`,
907+
},
908+
},
909+
});
910+
```
911+
912+
**Key Implementation Details:**
913+
914+
1. **Memoized Connection Management**
915+
916+
```typescript
917+
const getMcpClient = memoize(async () => {
918+
// Creates and caches a single MCP client instance
919+
});
920+
```
921+
922+
2. **Tool Invocation Wrapper**
923+
924+
```typescript
925+
async function invokeMcpTool(toolName: string, args: any) {
926+
const { tools } = await getMcpTools();
927+
const tool = tools[toolName];
928+
return await tool.execute(args);
929+
}
930+
```
931+
932+
3. **Comprehensive Error Handling**
933+
```typescript
934+
try {
935+
const result = await invokeMcpTool("search_subgraphs_by_keyword", {
936+
keyword,
937+
});
938+
return JSON.stringify(result, null, 2);
939+
} catch (error) {
940+
return JSON.stringify({
941+
error: error instanceof Error ? error.message : "Operation failed",
942+
});
943+
}
944+
```
945+
946+
### MCP Usage Examples
947+
948+
#### 1. Finding Subgraphs for a Contract
949+
950+
```
951+
User: "Find subgraphs for the ENS Registry contract 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e on mainnet"
952+
953+
AI Process:
954+
1. Uses getContractSubgraphs action
955+
2. Calls get_top_subgraph_deployments MCP tool
956+
3. Returns top 3 subgraphs indexing that contract
957+
958+
Response: Lists relevant ENS subgraphs with metadata like:
959+
- Subgraph ID
960+
- Deployment ID
961+
- Query fees
962+
- Network information
963+
```
964+
965+
#### 2. Searching for Subgraphs by Keyword
966+
967+
```
968+
User: "Find Uniswap V3 subgraphs"
969+
970+
AI Process:
971+
1. Uses searchSubgraphs action
972+
2. Calls search_subgraphs_by_keyword MCP tool
973+
3. Returns matching subgraphs ordered by signal
974+
975+
Response: Shows Uniswap V3 related subgraphs with:
976+
- Display names
977+
- Descriptions
978+
- Signal amounts
979+
- Current versions
980+
```
981+
982+
#### 3. Schema Introspection and Querying
983+
984+
```
985+
User: "What entities are available in the Uniswap V3 subgraph?"
986+
987+
AI Process:
988+
1. First searches for Uniswap V3 subgraphs (if needed)
989+
2. Uses getSubgraphSchema action with subgraph ID
990+
3. Calls get_schema_by_subgraph_id MCP tool
991+
4. Parses and explains available entities
992+
993+
Response: Lists entities like Pool, Token, Position, etc. with their fields
994+
```
995+
996+
#### 4. Advanced Query Execution
997+
998+
```
999+
User: "Show me the top 5 Uniswap V3 pools by TVL"
1000+
1001+
AI Process:
1002+
1. Identifies relevant subgraph (via search if needed)
1003+
2. Constructs appropriate GraphQL query
1004+
3. Uses executeMCPQuery action
1005+
4. Calls execute_query_by_subgraph_id MCP tool
1006+
1007+
GraphQL Query:
1008+
query {
1009+
pools(
1010+
first: 5
1011+
orderBy: totalValueLockedUSD
1012+
orderDirection: desc
1013+
) {
1014+
id
1015+
token0 { symbol }
1016+
token1 { symbol }
1017+
totalValueLockedUSD
1018+
volumeUSD
1019+
}
1020+
}
1021+
```
1022+
1023+
**Error Handling Examples:**
1024+
1025+
- **Invalid Contract Address**: "Contract address format is invalid"
1026+
- **Chain Not Supported**: "Chain 'unsupported-chain' not found"
1027+
- **Query Syntax Error**: "GraphQL syntax error: Expected Name, found }"
1028+
- **Schema Not Found**: "Schema not available for deployment ID 0x..."
1029+
1030+
**Best Practices:**
1031+
1032+
1. **Always provide chain parameter** when using `getContractSubgraphs`
1033+
2. **Use specific subgraph identifiers** (ID, deployment ID, or IPFS hash) for querying
1034+
3. **Handle pagination** for large result sets in queries
1035+
4. **Validate GraphQL syntax** before execution
1036+
5. **Check schema** before constructing complex queries
1037+
8071038
### Available Subgraphs
8081039
8091040
The integration includes several pre-configured subgraph endpoints:
@@ -995,10 +1226,11 @@ Here's a step-by-step guide to add a new subgraph endpoint (e.g., Compound Finan
9951226
9961227
Proper configuration of environment variables is crucial for the application to run correctly and securely. Store these in a `.env.local` file at the root of your `packages/nextjs` directory. **Never commit your `.env.local` file to version control.**
9971228
998-
1. **`GRAPH_API_KEY`** (For The Graph Protocol - `graph-querier.ts`)
1229+
1. **`GRAPH_API_KEY`** (For The Graph Protocol - Required for both legacy and MCP integrations)
9991230
10001231
- ⚠️ Use a development key with limited permissions for querying subgraphs.
1001-
- _Note: This key is used by `graph-querier.ts` for accessing The Graph subgraphs._
1232+
- _Note: This key is used by both `graph-querier.ts` (legacy) and `graph-mcp-provider.ts` (MCP) for accessing The Graph services._
1233+
- _MCP Usage: Used as Bearer token for authentication with The Graph's MCP server at `https://subgraphs.mcp.thegraph.com/sse`_
10021234

10031235
2. **`OPENAI_API_KEY`** (For OpenAI - `app/api/chat/route.ts`)
10041236

@@ -1286,7 +1518,15 @@ A multi-layered approach to ensure reliability.
12861518
- Verify variable formatting
12871519
- For Token API, ensure the `path` parameter in `app/api/token-proxy/route.ts` is correctly formed and that all required parameters for the specific external API endpoint are being passed. Check the proxy's server-side logs for details on the outgoing request.
12881520

1289-
4. **Token API Proxy Issues**
1521+
4. **MCP Connection Issues**
1522+
1523+
- **Authentication Failures**: Verify `GRAPH_API_KEY` is correctly set and valid for MCP access
1524+
- **Connection Timeout**: MCP server may be temporarily unavailable, check The Graph's status page
1525+
- **Tool Not Found**: Use `listMCPTools` action to verify available tools on the MCP server
1526+
- **Invalid Parameters**: Ensure correct parameter format (e.g., chain names: 'mainnet', not 'ethereum')
1527+
- **SSE Connection Issues**: Server-Sent Events transport may fail due to network/proxy issues
1528+
1529+
5. **Token API Proxy Issues**
12901530
- **Misconfigured URL/Auth**: Double-check `NEXT_PUBLIC_GRAPH_API_URL`, `NEXT_PUBLIC_GRAPH_API_KEY`, and `NEXT_PUBLIC_GRAPH_TOKEN` (and their non-public equivalents if used) in your `.env.local` file.
12911531
- **Path resolution**: Ensure the `path` parameter sent to `/api/token-proxy` correctly maps to the intended external API endpoint.
12921532
- **External API Downtime/Errors**: The external Token API itself might be having issues. Check its status page if available. The proxy should forward error messages from the external API.

0 commit comments

Comments
 (0)