arcade-mcp/examples/langchain-ts/langgraph-with-user-auth.ts
Eric Gustin 3424ec8219
MCP Local (#563)
Versions:
* arcade-mcp\==1.0.0rc1
* arcade-mcp-server\==1.0.0rc1
* arcade-core\==2.5.0rc1
* arcade-tdk\==2.6.0rc1
* arcade-serve\==2.2.0rc1

### Summary
Adds first-class MCP support across Arcade, introduces a new MCP server
and CLI, unifies the project under the arcade-mcp name, overhauls
templates/scaffolding, and improves developer tooling, secrets
management, and examples.

### Highlights
- **MCP Server & Core**
- New MCP server with stdio and HTTP/SSE transports, session management,
resumability, and lifecycle handling.
- FastAPI-like `MCPApp` for building servers with lazy init; integrated
worker+MCP HTTP app option.
- Middleware system (logging and error handling), robust exception
hierarchy, and Pydantic-based settings.
- Async-safe managers for tools, resources, and prompts backed by
registries and locks.
- Developer-facing, transport-agnostic runtime context interfaces (logs,
tools, prompts, resources, sampling, UI, notifications).
- Conversion from Arcade ToolDefinition to MCP tool schema; OpenAI JSON
tool schema converter.
  - Parser supports `@app.tool`/`@app.tool(...)` decorators.

- **CLI**
  - New `mcp` command to run MCP servers with stdio or HTTP/SSE.
- New `secret` command to set/list/unset tool secrets (supports .env
input, preserves original casing for lookups).
- `new` command refactored; option to create a full toolkit package with
scaffolding.
  - `chat` command removed.
- `serve.py` imports updated to `arcade_serve.fastapi.telemetry`;
version retrieval now uses `arcade-mcp`.
  - `show.py` refactor to use new local catalog utilities.
- `display_tool_details` improved: adds “Default” column and handles
nested properties.

- **Configuration & Discovery**
- New `configure.py` to set up Claude Desktop, Cursor, and VS Code to
connect to local or Arcade Cloud MCP servers.
- Discovery utilities to find/install toolkits, build `ToolCatalog`s,
analyze files for tools, load kits from directories (pyproject parsing),
and build minimal toolkits.
- Better handling of provider API key resolution and evaluation suite
loading.

- **Templates & Scaffolding**
- Reorganized template structure (minimal vs full); moved
`.pre-commit-config.yaml`, `.ruff.toml`, license, Makefile, README,
tests, and tools layout to correct paths.
  - Minimal template adds `.env.example` for runtime secret injection.
- Template pyproject updated for MCP servers; includes sample server
with greeting and secret-reveal tools.
  - Authorization flow in templates simplified.

- **Repo-wide Renaming & Examples**
- Migrates references from `arcade-ai` to `arcade-mcp` across READMEs,
scripts, and package metadata.
- Examples updated (LangChain/LangGraph/AI SDK/TypeScript) and package
name changed to `arcade-mcp-sdk`.

- **Evals & Core Utilities**
- Evals now use OpenAI tooling format (`OpenAIToolList`, `to_openai`);
`tool_eval` takes `provider_api_key`.
- Core utilities: fixed `does_function_return_value` by dedenting before
parse; version bump to `2.5.0rc1` and dependency cleanup.

- **Tooling & CI**
- `setup-uv-env` action splits toolkit vs contrib dependency
installation.
- Pre-commit: excludes `libs/arcade-mcp-server/mkdocs.yml` and
`libs/tests/` from YAML and Ruff hooks; Ruff per-file ignores (e.g.,
C901 in `libs/**/*.py`, TRY400 in server docs paths).
- Makefile updates for uv env setup, quality checks, tests, builds, and
new `shell` target.
  - Added Makefile to MCP server library to streamline dev workflow.

- **Cleanup**
  - Removed `claude.json` config.
- Simplified stdio entrypoint; removed unused imports (`arcade_gmail`,
`arcade_search`).

### Breaking Changes
- **CLI**: `chat` command removed; use `mcp`, `secret`, and updated
`new`.
- **Naming**: All users should update references from `arcade-ai` to
`arcade-mcp`.
- **Templates**: File paths moved; downstream scripts referencing old
template locations may need updates.

### Getting Started
- Run an MCP server:
  - `arcade mcp --stdio --toolkits your_toolkit`
  - `arcade mcp --http --toolkits your_toolkit`
- Manage secrets:
  - `arcade secret set your_toolkit KEY=value`
  - `arcade secret list your_toolkit`
  - `arcade secret unset your_toolkit KEY`
- Configure clients:
- `arcade configure` to set up Claude Desktop, Cursor, and VS Code for
local/Arcade Cloud MCP.

---------

Co-authored-by: Sam Partee <sam@arcade-ai.com>
Co-authored-by: Shub <125150494+shubcodes@users.noreply.github.com>
2025-09-25 15:28:15 -07:00

148 lines
4.3 KiB
TypeScript

import { pathToFileURL } from "node:url";
import { Arcade } from "@arcadeai/arcadejs";
import { toZod } from "@arcadeai/arcadejs/lib";
import type { AIMessage } from "@langchain/core/messages";
import { tool } from "@langchain/core/tools";
import { MessagesAnnotation, StateGraph } from "@langchain/langgraph";
import { ToolNode } from "@langchain/langgraph/prebuilt";
import { ChatOpenAI } from "@langchain/openai";
// Initialize Arcade with API key from environment
const arcade = new Arcade();
// Replace with your application's user ID (e.g. email address, UUID, etc.)
const USER_ID = "user@example.com";
// Initialize tools from GitHub toolkit
const githubToolkit = await arcade.tools.list({ toolkit: "github", limit: 30 });
const arcadeTools = toZod({
tools: githubToolkit.items,
client: arcade,
userId: USER_ID,
});
// Convert Arcade tools to LangGraph tools
const tools = arcadeTools.map(({ name, description, execute, parameters }) =>
tool(execute, {
name,
description,
schema: parameters,
}),
);
// Initialize the prebuilt tool node
const toolNode = new ToolNode(tools);
// Create a language model instance and bind it with the tools
const model = new ChatOpenAI({
model: "gpt-4o",
apiKey: process.env.OPENAI_API_KEY,
});
const modelWithTools = model.bindTools(tools);
// Function to check if a tool requires authorization
async function requiresAuth(toolName: string): Promise<{
needsAuth: boolean;
id: string;
authUrl: string;
}> {
const authResponse = await arcade.tools.authorize({
tool_name: toolName,
user_id: USER_ID,
});
return {
needsAuth: authResponse.status === "pending",
id: authResponse.id ?? "",
authUrl: authResponse.url ?? "",
};
}
// Function to invoke the model and get a response
async function callAgent(
state: typeof MessagesAnnotation.State,
): Promise<typeof MessagesAnnotation.Update> {
const messages = state.messages;
const response = await modelWithTools.invoke(messages);
return { messages: [response] };
}
// Function to determine the next step in the workflow based on the last message
async function shouldContinue(
state: typeof MessagesAnnotation.State,
): Promise<string> {
const lastMessage = state.messages[state.messages.length - 1] as AIMessage;
if (lastMessage.tool_calls?.length) {
for (const toolCall of lastMessage.tool_calls) {
const { needsAuth } = await requiresAuth(toolCall.name);
if (needsAuth) {
return "authorization";
}
}
return "tools"; // Proceed to tool execution if no authorization is needed
}
return "__end__"; // End the workflow if no tool calls are present
}
// Function to handle authorization for tools that require it
async function authorize(
state: typeof MessagesAnnotation.State,
): Promise<typeof MessagesAnnotation.Update> {
const lastMessage = state.messages[state.messages.length - 1] as AIMessage;
for (const toolCall of lastMessage.tool_calls || []) {
const toolName = toolCall.name;
const { needsAuth, id, authUrl } = await requiresAuth(toolName);
if (needsAuth) {
// Prompt the user to visit the authorization URL
console.log(`Visit the following URL to authorize: ${authUrl}`);
// Wait for the user to complete the authorization
const response = await arcade.auth.waitForCompletion(id);
if (response.status !== "completed") {
throw new Error("Authorization failed");
}
}
}
return { messages: [] };
}
// Build the workflow graph
const workflow = new StateGraph(MessagesAnnotation)
.addNode("agent", callAgent)
.addNode("tools", toolNode)
.addNode("authorization", authorize)
.addEdge("__start__", "agent")
.addConditionalEdges("agent", shouldContinue, [
"authorization",
"tools",
"__end__",
])
.addEdge("authorization", "tools")
.addEdge("tools", "agent");
// Compile the graph
const graph = workflow.compile();
const main = async () => {
// Define the input messages from the user
const inputs = {
messages: [
{
role: "user",
content: "Star arcadeai/arcade-mcp on github",
},
],
};
// Run the graph and stream the outputs
const stream = await graph.stream(inputs, { streamMode: "values" });
for await (const chunk of stream) {
// Print the last message in the chunk
console.log(chunk.messages[chunk.messages.length - 1].content);
}
};
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch(console.error);
}
export { graph };