Skip to content

Chapter 8 · Connecting the MCP Tool Ecosystem ​

Chapter goals: Understand MCP's position in the Agent architecture, master连接/认证/工具筛选 with useMcpConnection(), and safely接入 third-party services.

8.1 Why MCP Is Needed ​

Tools from Chapter 6 require you to写 yourself:接 Linear requires one tool, 接 Notion another, GitHub yet another — each服务 is a套 API wrapper.

MCP (Model Context Protocol) standardizes this: the service provider implements an MCP server exposing tools; any protocol-supporting agent connects directly and uses them. One对接, everywhere usable:

text
Your Agent ──┬── 自有工具 (defineTool)      → Business logic
             ├── 沙箱内置工具                → Files and shell
             └── MCP 工具 (useMcpConnection) → Linear/Notion/GitHub… ecosystem

8.2 Connecting an MCP Server ​

Call useMcpConnection() inside the agent function body:

typescript
// src/agents/project-assistant.ts
'use agent';
import { useMcpConnection, useModel } from '@flue/runtime';

export function ProjectAssistant() {
  useModel('anthropic/claude-sonnet-4-6');

  // Connect to Linear's official MCP server
  useMcpConnection({
    name: 'linear',                        // Connection name; used to生成 tool prefix
    url: 'https://mcp.linear.app/mcp',     // Server address
    auth: process.env.LINEAR_API_KEY,      // Bearer token authentication
  });

  return 'Manage issues and projects on Linear for the team.';
}

Runtime behavior: when the agent starts processing a message, itestablishes the connection, auto-discovers all server tools and加入 the toolset; the connection复用 during the instance lifetime — you don't need to manually开/关 connections. MCP tools are named mcp__<server>__<tool> (e.g., mcp__linear__create_issue) to avoid命名冲突 with your own tools.

8.3 Authentication: Static Token and Dynamic Function ​

Many hosted MCP servers follow the MCP authorization model (OAuth 2.1), expecting a Bearer token. auth supports两种形态:

typescript
'use agent';
import { useMcpConnection, useInitialData } from '@flue/runtime';

export function MultiTenantAssistant() {
  const { userId } = useInitialData<{ userId: string }>();

  useMcpConnection({
    name: 'linear',
    url: 'https://mcp.linear.app/mcp',
    // Dynamic auth: function解析s before each request; naturally supports rotation and revocation
    auth: () => tokenStore.get(userId, 'linear'),
  });

  return 'Help users manage their Linear tasks.';
}

Two安全边界:

  • Flue does not store or管理 your tokens — OAuth流程, token storage, refresh logic全部由你的应用负责;
  • When user中途授权 is needed, declare the connection conditionally: flip a persistent flag after OAuth completes; from the next message onward the agent拥有 that server's tools.

8.4 Tool Filtering and Connection Reuse ​

Servers动辄暴露几十个工具, each占用模型上下文. Use a tools whitelist to挂 only what's needed:

typescript
'use agent';
import { useModel, useMcpConnection } from '@flue/runtime';
import { linear } from '../connections/linear.ts'; // defineMcpConnection definition

export function IssueReader() {
  useModel('anthropic/claude-haiku-4-5');
  // Reuse the shared definition, but narrowly filter tools
  useMcpConnection({ ...linear, tools: ['search_issues', 'get_issue'] });
  return 'Query and report project issue status.';
}
typescript
// src/connections/linear.ts —— defineMcpConnection: define once, reuse everywhere
import { defineMcpConnection } from '@flue/runtime';

export const linear = defineMcpConnection({
  name: 'linear',
  url: 'https://mcp.linear.app/mcp',
  auth: process.env.LINEAR_API_KEY,
});

Note: writing a tool in the whitelist that the server doesn't存在 causes connection failure报错; optional: true lets the connection degrade gracefully (the model is told该组工具暂不可用).

8.5 Security Notes ​

typescript
// ⚠️ An untrusted third-party MCP server is equivalent to a third-party dependency:
// its tool descriptions enter your prompt,
// its return results enter the conversation.
//
//防护清单:
// 1. Limit exposure with a tools whitelist
useMcpConnection({ ...untrusted, tools: ['read_only_search'] });
// 2.优先 use official/trusted-source servers
// 3. For high-privilege operations保留自有 defineTool implementation (with approval flow)
// 4. Monitor MCP tool call logs in production (see Observability chapter)

Advanced usage: createMcpConnection(definition) is a lower-level interface — connects directly to the server, discovers tools, and returns ToolDefinition[], letting trusted application code pre-filter before mounting.

8.6 Chapter Summary ​

  • MCP turns "write a套 tool per service" into "connect and use" standard协议;
  • useMcpConnection() auto-discovers tools, naming mcp__<server>__<tool>;
  • auth accepts static string or dynamic function (解析s before each request); token management is your responsibility;
  • tools whitelist controls上下文占用 and exposure面; optional: true allows降级;
  • Treat third-party servers as third-party dependencies — evaluate carefully, whitelist as fallback.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. After connecting via useMcpConnection, how are server tools named in the toolset?

2. What is the意义 of passing a function而非 string to auth?

3. What happens if a tool in the whitelist does not exist on the server?

4. Which is the recommended security practice for third-party MCP servers?

🛠️ Hands-On Exercises ​

  1. Connect to any公开 MCP server (e.g., GitHub official); list all discovered tool names and test two of them.
  2. Use a tools whitelist to砍 the tool surface to under 3; compare the model's tool-selection accuracy before and after.
  3. Implement a conditional MCP mounting flow: connect only after the user inputs their API Key.

MCP mastered. Next, learn Sub-agents: expert delegation.