
File Context MCP
这个服务器提供了一个 API,可以使用本地文件的上下文来查询大型语言模型,支持各种模型和文件类型,以实现上下文感知的响应。
README
文件上下文 MCP (模型上下文处理器)
概述
File Context MCP 是一个基于 TypeScript 的应用程序,它提供了一个 API,用于使用来自本地文件的上下文查询大型语言模型 (LLM)。它支持多个 LLM 提供商(Ollama 和 Together.ai),并且可以处理各种文件类型以生成上下文相关的响应。
核心功能
1. 文件系统导航
- 动态文件和目录遍历
- 支持多种文件类型(
.txt
、.md
、.ts
、.json
等) - 使用清理的安全路径处理
import path from 'path';
export const fileUtils = {
isTextFile(filePath: string): boolean {
const textExtensions = [
'.txt', '.md', '.js', '.ts', '.json', '.yaml', '.yml',
'.html', '.css', '.csv', '.xml', '.log', '.env',
'.jsx', '.tsx', '.py', '.java', '.cpp', '.c', '.h'
];
return textExtensions.includes(path.extname(filePath).toLowerCase());
},
2. 上下文处理
- 用于 LLM 查询的智能上下文格式化
- 上下文截断以处理大型文件
- 用于目录查询的文件内容聚合
export const promptUtils = {
formatContextPrompt(context: string, query: string): string {
return `
You are an AI assistant analyzing the following content:
---BEGIN CONTEXT---
${context}
---END CONTEXT---
Please respond to the following query:
${query}
Base your response only on the information provided in the context above.
`;
},
truncateContext(context: string, maxLength: number = 4000): string {
if (context.length <= maxLength) return context;
// Try to truncate at a natural break point
const truncated = context.slice(0, maxLength);
const lastNewline = truncated.lastIndexOf('\n');
if (lastNewline > maxLength * 0.8) {
return truncated.slice(0, lastNewline) + '\n... (truncated)';
}
return truncated + '... (truncated)';
}
};
3. 多模型支持
- Ollama (本地) 集成
- Together.ai (云) 集成
- 可扩展的模型接口设计
export interface LLMResponse {
text: string;
model: string;
error?: string;
}
export class ModelInterface {
async queryOllama(prompt: string, context: string): Promise<LLMResponse> {
try {
const response = await axios.post(`${config.ollamaBaseUrl}/api/generate`, {
model: config.modelName,
prompt: this.formatPrompt(prompt, context),
stream: false
});
return {
if (!response.data || !response.data.response) {
throw new Error('Invalid response from Ollama');
}
} catch (error) {
return {
text: response.data.response,
model: 'ollama'
};
} catch (error) {
console.error('Ollama error:', error);
return {
text: '',
model: 'ollama',
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
model: config.modelName,
async queryTogether(prompt: string, context: string): Promise<LLMResponse> {
try {
const response = await axios.post(
'https://api.together.xyz/inference',
{
model: config.modelName,
prompt: this.formatPrompt(prompt, context),
max_tokens: 512,
},
{
headers: {
Authorization: `Bearer ${config.togetherApiKey}`
}
}
);
return {
return {
text: response.data.output.text,
model: 'together'
};
} catch (error) {
return {
text: '',
model: 'together',
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
private formatPrompt(prompt: string, context: string): string {
return `Context: ${context}\n\nQuestion: ${prompt}`;
}
}
架构
核心组件
-
服务器 (server.ts)
- Express.js REST API 实现
- 使用 multer 的文件上传/删除处理
- 请求验证和路由
- OpenAPI/Swagger 集成
-
FileSystemTools (core/fileSystem.ts)
- 文件和目录操作
- 内容读取和解析
- 目录遍历
- 安全文件删除
- 文件操作的错误处理
-
ModelInterface (core/modelInterface.ts)
- 多 LLM 提供商支持(Ollama、Together.ai)
- 响应格式化和错误处理
- 可配置的模型参数
- 统一的查询接口
-
实用程序模块
fileUtils
: 文件类型检测、路径清理、大小格式化promptUtils
: 上下文格式化、智能截断validators
: 路径、查询和模型验证logger
: 具有级别的结构化日志记录
-
配置 (config/config.ts)
- 环境变量管理
- API 密钥和端点
- 模型配置
- 服务器设置
-
API 规范 (resources/file-context-api.yml)
- OpenAPI 3.0 文档
- 请求/响应模式
- 端点文档
- 错误响应定义
API 端点
1. 列出文件
GET /api/files
查询参数:
- path: string (可选,默认为 './')
响应:
- 包含文件/目录详细信息的 FileInfo 对象数组
2. 上传文件
POST /api/files/upload
Content-Type: multipart/form-data
Body:
- file: File (必须是文本文件,最大 5MB)
响应:
{
"message": "文件上传成功",
"file": {
"name": string,
"size": string,
"path": string
}
}
3. 删除文件
DELETE /api/files/{filename}
参数:
- filename: string (要删除的文件名)
响应:
{
"message": "文件删除成功"
}
4. 使用上下文查询
POST /api/query
Body:
{
"path": string,
"query": string,
"model": "ollama" | "together"
}
Response:
{
"text": string,
"model": string,
"error?: string
}
设置和配置
- 环境变量
TOGETHER_API_KEY=your_api_key_here
OLLAMA_BASE_URL=http://localhost:11434
MODEL_NAME=llama2
PORT=3001
- 安装
npm install
通过 Smithery 安装
要通过 Smithery 为 Claude Desktop 自动安装 File Context MCP:
npx @smithery/cli@latest install @compiledwithproblems/file-context-mcp --client claude
- 运行应用程序
# 开发
npm run dev
# 生产
npm run build
npm start
工作原理
-
文件处理流程
- 接收请求 → 路径验证 → 文件读取 → 内容提取
- 目录处理包括递归文件读取
- 基于文件类型的内容过滤
- 文件上传经过类型和大小验证
- 使用路径验证的安全文件删除
-
上下文处理
- 文件内容被聚合
- 上下文以清晰的边界格式化
- 大型上下文被智能截断
- 提示格式化为 LLM 理解添加结构
-
模型集成
- 用于不同 LLM 提供商的统一接口
- 错误处理和响应规范化
- 可配置的模型参数
安全特性
-
路径清理
- 预防目录遍历攻击
- 路径验证和规范化
- 安全文件类型检查
-
文件上传安全
- 文件类型验证
- 文件大小限制(最大 5MB)
- 安全文件存储
- 安全文件删除
-
输入验证
- 查询内容验证
- 模型类型验证
- 路径结构验证
- 文件内容验证
支持的文件类型
该应用程序支持以下基于文本的文件类型:
- 文档:
.txt
、.md
- 代码文件:
.js
、.ts
、.jsx
、.tsx
、.py
、.java
、.cpp
、.c
、.h
- 配置:
.json
、.yaml
、.yml
、.env
- Web 文件:
.html
、.css
- 数据文件:
.csv
、.xml
、.log
文件类型验证在以下情况下强制执行:
- 文件上传
- 上下文处理
- 文件读取操作
最大文件大小:每个文件 5MB
错误处理
该应用程序实现了全面的错误处理:
- 文件系统错误
- API 响应错误
- 无效输入错误
- 模型特定错误
- 文件上传/删除错误
开发
项目结构
file-context-mcp/
├── src/
│ ├── server.ts # 主应用程序服务器
│ ├── core/ # 核心功能
│ │ ├── fileSystem.ts # 文件操作处理
│ │ └── modelInterface.ts # LLM 提供商集成
│ ├── utils/ # 实用程序函数
│ │ ├── fileUtils.ts # 文件类型和路径实用程序
│ │ ├── promptUtils.ts # 提示格式化
│ │ ├── validators.ts # 输入验证
│ │ └── logger.ts # 应用程序日志记录
│ ├── config/ # 配置
│ │ └── config.ts # 环境和应用程序配置
│ └── resources/ # API 规范
│ └── file-context-api.yml # OpenAPI 规范
├── storage/ # 文件存储目录
│ ├── code-samples/ # 示例代码文件
│ └── notes/ # 文档和笔记
├── postman/ # API 测试
│ └── File-Context-MCP.postman_collection.json # Postman 集合
├── dist/ # 编译后的输出
└── node_modules/ # 依赖项
添加新功能
-
新文件类型
- 将扩展名添加到
fileUtils.isTextFile()
- 如果需要,实现特定的处理程序
- 将扩展名添加到
-
新模型提供商
- 扩展
ModelInterface
类 - 将提供商添加到
validators.isValidModel()
- 实现提供商特定的错误处理
- 扩展
测试
Postman 集合
该项目包含一个 Postman 集合 (postman/File-Context-MCP.postman_collection.json
),用于测试所有 API 端点。 要使用它:
-
导入集合
- 打开 Postman
- 单击“导入”按钮
- 选择或拖动
File-Context-MCP.postman_collection.json
文件
-
可用请求
File-Context-MCP ├── List files │ └── GET http://localhost:3001/api/files?path=./storage ├── Query │ └── POST http://localhost:3001/api/query (single file analysis) ├── Analyze multiple files │ └── POST http://localhost:3001/api/query (directory analysis) └── File Upload └── POST http://localhost:3001/api/files/upload
-
测试文件操作
- List Files: 查看存储目录的内容
- Upload File: 使用 form-data,键为 "file",并选择一个文本文件
- Query File: 使用 LLM 分析单个文件内容
- Analyze Directory: 使用 LLM 处理多个文件
-
示例查询
// 单个文件分析 { "path": "./storage/code-samples/example.ts", "query": "Explain what this TypeScript code does", "model": "ollama" } // 目录分析 { "path": "./storage", "query": "What types of files are in this directory and summarize their contents?", "model": "ollama" }
-
文件上传指南
- 使用 "File Upload" 请求
- 在 Body 选项卡中选择 "form-data"
- 添加键 "file",类型为 "File"
- 选择支持的文本文件(请参阅支持的文件类型)
- 最大文件大小:5MB
手动测试
- 使用
/storage
中提供的测试文件 - 测试不同的文件类型和查询
- 验证模型响应和错误处理
- 测试文件大小限制和类型限制
环境设置
确保:
- 服务器正在运行 (
npm run dev
) - 配置环境变量
- Ollama 在本地运行(对于 Ollama 模型)
- 设置 Together.ai API 密钥(对于 Together 模型)
未来考虑
- 如何有效地处理大型文件
- 扩展支持的文件类型
- 优化上下文处理
- 添加对响应的流式传输支持
- 实施速率限制和缓存
该项目演示了现代 TypeScript/Node.js 实践,重点是模块化、类型安全和错误处理,同时为基于文件的上下文的 LLM 交互提供灵活的接口。
推荐服务器
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Excel MCP Server
一个模型上下文协议服务器,使 AI 助手能够读取和写入 Microsoft Excel 文件,支持诸如 xlsx、xlsm、xltx 和 xltm 等格式。
Playwright MCP Server
提供一个利用模型上下文协议的服务器,以实现类人浏览器的自动化,该服务器使用 Playwright,允许控制浏览器行为,例如导航、元素交互和滚动。
Claude Code MCP
一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。
Apple MCP Server
通过 MCP 协议与 Apple 应用(如“信息”、“备忘录”和“通讯录”)进行交互,从而使用自然语言发送消息、搜索和打开应用内容。
contentful-mcp
在你的 Contentful Space 中更新、创建、删除内容、内容模型和资源。
serper-search-scrape-mcp-server
这个 Serper MCP 服务器支持搜索和网页抓取,并且支持 Serper API 引入的所有最新参数,例如位置信息。
The Verge News MCP Server
提供从The Verge的RSS feed获取和搜索新闻的工具,允许用户获取今日新闻、检索过去一周的随机文章,以及在最近的Verge内容中搜索特定关键词。
MCP Server Trello
通过 Trello API 促进与 Trello 看板的交互,提供速率限制、类型安全、输入验证和错误处理等功能,以实现对卡片、列表和看板活动的无缝管理。