文件上下文 MCP(模型上下文处理器)
概述
文件上下文 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 集成
- 文件系统工具(core/fileSystem.ts)
- 文件和目录操作
- 内容读取和解析
- 目录遍历
- 安全文件删除
- 文件操作的错误处理
- 模型接口(core/modelInterface.ts)
- 多个 LLM 提供商支持(Ollama、Together.ai)
- 响应格式和错误处理
- 可配置模型参数
- 统一查询接口
- 实用模块
fileUtils
:文件类型检测、路径清理、大小格式化promptUtils
:上下文格式化、智能截断validators
:路径、查询和模型验证logger
:具有级别的结构化日志记录
- 配置(config/config.ts)
- API 规范(resources/file-context-api.yml)
- OpenAPI 3.0 文档
- 请求/响应模式
- 端点文档
- 错误响应定义
API 端点
1. 列出文件
GET /api/files
Query params:
- path: string (optional, defaults to './')
Response:
- Array of FileInfo objects with file/directory details
2.上传文件
POST /api/files/upload
Content-Type: multipart/form-data
Body:
- file: File (must be a text file, max 5MB)
Response:
{
"message": "File uploaded successfully",
"file": {
"name": string,
"size": string,
"path": string
}
}
3.删除文件
DELETE /api/files/{filename}
Params:
- filename: string (name of file to delete)
Response:
{
"message": "File deleted successfully"
}
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
- 安装
通过 Smithery 安装
要通过Smithery自动为 Claude Desktop 安装 File Context MCP:
npx @smithery/cli@latest install @compiledwithproblems/file-context-mcp --client claude
- 运行应用程序
# Development
npm run dev
# Production
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 # Main application server
│ ├── core/ # Core functionality
│ │ ├── fileSystem.ts # File operations handling
│ │ └── modelInterface.ts # LLM provider integrations
│ ├── utils/ # Utility functions
│ │ ├── fileUtils.ts # File type & path utilities
│ │ ├── promptUtils.ts # Prompt formatting
│ │ ├── validators.ts # Input validation
│ │ └── logger.ts # Application logging
│ ├── config/ # Configuration
│ │ └── config.ts # Environment & app config
│ └── resources/ # API specifications
│ └── file-context-api.yml # OpenAPI spec
├── storage/ # File storage directory
│ ├── code-samples/ # Example code files
│ └── notes/ # Documentation & notes
├── postman/ # API testing
│ └── File-Context-MCP.postman_collection.json # Postman collection
├── dist/ # Compiled output
└── node_modules/ # Dependencies
添加新功能
- 新的文件类型
- 为
fileUtils.isTextFile()
添加扩展 - 如果需要,实现特定的处理程序
- 新模型提供者
- 扩展
ModelInterface
类 - 将提供程序添加到
validators.isValidModel()
- 实现特定于提供程序的错误处理
测试
邮差收藏
该项目包含一个 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 :查看存储目录的内容
- 上传文件:使用带有键“文件”的表单数据并选择一个文本文件
- 查询文件:使用 LLM 分析单个文件内容
- 分析目录:使用 LLM 处理多个文件
- 示例查询
// Single file analysis
{
"path": "./storage/code-samples/example.ts",
"query": "Explain what this TypeScript code does",
"model": "ollama"
}
// Directory analysis
{
"path": "./storage",
"query": "What types of files are in this directory and summarize their contents?",
"model": "ollama"
}
- 文件上传指南
- 使用“文件上传”请求
- 在 Body 选项卡中选择“form-data”
- 添加“文件”类型的键“文件”
- 选择支持的文本文件(请参阅支持的文件类型)
- 最大文件大小:5MB
手动测试
- 使用
/storage
中提供的测试文件 - 测试不同的文件类型和查询
- 验证模型响应和错误处理
- 测试文件大小限制和类型限制
环境设置
请确保:
- 让服务器运行(
npm run dev
) - 配置环境变量
- 让 Ollama 在本地运行(适用于 Ollama 模型)
- 设置 Together.ai API 密钥(用于 Together 模型)
未来考虑
- 如何高效处理大文件
- 扩展支持的文件类型
- 优化上下文处理
- 添加对响应的流支持
- 实施速率限制和缓存
该项目展示了现代 TypeScript/Node.js 实践,重点关注模块化、类型安全性和错误处理,同时为 LLM 与基于文件的上下文交互提供了灵活的接口。