# Directory Structure ``` ├── .gitignore ├── overleaf-git-client.js ├── overleaf-mcp-server.js ├── package-lock.json ├── package.json ├── projects.example.json └── README.md ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` node_modules/ temp/ projects.json .env *.log ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Overleaf MCP Server An MCP (Model Context Protocol) server that provides access to Overleaf projects via Git integration. This allows Claude and other MCP clients to read LaTeX files, analyze document structure, and extract content from Overleaf projects. ## Features - 📄 **File Management**: List and read files from Overleaf projects - 📋 **Document Structure**: Parse LaTeX sections and subsections - 🔍 **Content Extraction**: Extract specific sections by title - 📊 **Project Summary**: Get overview of project status and structure - 🏗️ **Multi-Project Support**: Manage multiple Overleaf projects ## Installation 1. Clone this repository 2. Install dependencies: ```bash npm install ``` 3. Set up your projects configuration: ```bash cp projects.example.json projects.json ``` 4. Edit `projects.json` with your Overleaf credentials: ```json { "projects": { "default": { "name": "My Paper", "projectId": "YOUR_OVERLEAF_PROJECT_ID", "gitToken": "YOUR_OVERLEAF_GIT_TOKEN" } } } ``` ## Getting Overleaf Credentials 1. **Git Token**: - Go to Overleaf Account Settings → Git Integration - Click "Create Token" 2. **Project ID**: - Open your Overleaf project - Find it in the URL: `https://www.overleaf.com/project/[PROJECT_ID]` ## Claude Desktop Setup Add to your Claude Desktop configuration file: **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` **Linux**: `~/.config/claude/claude_desktop_config.json` ```json { "mcpServers": { "overleaf": { "command": "node", "args": [ "/path/to/OverleafMCP/overleaf-mcp-server.js" ] } } } ``` Restart Claude Desktop after configuration. ## Available Tools ### `list_projects` List all configured projects. ### `list_files` List files in a project (default: .tex files). - `extension`: File extension filter (optional) - `projectName`: Project identifier (optional, defaults to "default") ### `read_file` Read a specific file from the project. - `filePath`: Path to the file (required) - `projectName`: Project identifier (optional) ### `get_sections` Get all sections from a LaTeX file. - `filePath`: Path to the LaTeX file (required) - `projectName`: Project identifier (optional) ### `get_section_content` Get content of a specific section. - `filePath`: Path to the LaTeX file (required) - `sectionTitle`: Title of the section (required) - `projectName`: Project identifier (optional) ### `status_summary` Get a comprehensive project status summary. - `projectName`: Project identifier (optional) ## Usage Examples ``` # List all projects Use the list_projects tool # Get project overview Use status_summary tool # Read main.tex file Use read_file with filePath: "main.tex" # Get Introduction section Use get_section_content with filePath: "main.tex" and sectionTitle: "Introduction" # List all sections in a file Use get_sections with filePath: "main.tex" ``` ## Multi-Project Usage To work with multiple projects, add them to `projects.json`: ```json { "projects": { "default": { "name": "Main Paper", "projectId": "project-id-1", "gitToken": "token-1" }, "paper2": { "name": "Second Paper", "projectId": "project-id-2", "gitToken": "token-2" } } } ``` Then specify the project in tool calls: ``` Use get_section_content with projectName: "paper2", filePath: "main.tex", sectionTitle: "Methods" ``` ## File Structure ``` OverleafMCP/ ├── overleaf-mcp-server.js # Main MCP server ├── overleaf-git-client.js # Git client library ├── projects.json # Your project configuration (gitignored) ├── projects.example.json # Example configuration ├── package.json # Dependencies └── README.md # This file ``` ## Security Notes - `projects.json` is gitignored to protect your credentials - Never commit real project IDs or Git tokens - Use the provided `projects.example.json` as a template ## License MIT License ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "overleaf-mcp", "version": "1.0.0", "description": "MCP server for Overleaf Git integration", "main": "overleaf-mcp-server.js", "scripts": { "start": "node overleaf-mcp-server.js" }, "dependencies": { "@modelcontextprotocol/sdk": "^0.5.0" } } ``` -------------------------------------------------------------------------------- /projects.example.json: -------------------------------------------------------------------------------- ```json { "projects": { "default": { "name": "My Paper", "projectId": "YOUR_PROJECT_ID", "gitToken": "YOUR_GIT_TOKEN" }, "project2": { "name": "Another Paper", "projectId": "ANOTHER_PROJECT_ID", "gitToken": "ANOTHER_GIT_TOKEN" } } } ``` -------------------------------------------------------------------------------- /overleaf-git-client.js: -------------------------------------------------------------------------------- ```javascript const { exec } = require('child_process'); const fs = require('fs').promises; const path = require('path'); const { promisify } = require('util'); const execAsync = promisify(exec); class OverleafGitClient { constructor(gitToken, projectId, tempDir = './temp') { this.gitToken = gitToken; this.projectId = projectId; this.tempDir = tempDir; this.repoUrl = `https://git:${gitToken}@git.overleaf.com/${projectId}`; this.localPath = path.join(tempDir, projectId); } async cloneOrPull() { try { await fs.access(this.localPath); await execAsync(`cd "${this.localPath}" && git pull`, { env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } }); } catch { await fs.mkdir(this.tempDir, { recursive: true }); await execAsync(`git clone "${this.repoUrl}" "${this.localPath}"`, { env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } }); } } async listFiles(extension = '.tex') { await this.cloneOrPull(); const files = []; async function walk(dir) { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory() && entry.name !== '.git') { await walk(fullPath); } else if (entry.isFile() && (!extension || entry.name.endsWith(extension))) { files.push(fullPath); } } } await walk(this.localPath); return files.map(f => path.relative(this.localPath, f)); } async readFile(filePath) { await this.cloneOrPull(); const fullPath = path.join(this.localPath, filePath); return await fs.readFile(fullPath, 'utf8'); } async getSections(filePath) { const content = await this.readFile(filePath); const sections = []; const sectionRegex = /\\(part|chapter|section|subsection|subsubsection|paragraph|subparagraph)\*?\{([^}]+)\}/g; let match; let lastIndex = 0; while ((match = sectionRegex.exec(content)) !== null) { const type = match[1]; const title = match[2]; const startIndex = match.index; if (sections.length > 0) { sections[sections.length - 1].content = content.substring(lastIndex + match[0].length, startIndex).trim(); } sections.push({ type, title, startIndex, content: '' }); lastIndex = startIndex; } if (sections.length > 0) { sections[sections.length - 1].content = content.substring(lastIndex + sections[sections.length - 1].title.length + 3).trim(); } return sections; } async getSection(filePath, sectionTitle) { const sections = await this.getSections(filePath); return sections.find(s => s.title === sectionTitle); } async getSectionsByType(filePath, type) { const sections = await this.getSections(filePath); return sections.filter(s => s.type === type); } } module.exports = OverleafGitClient; ``` -------------------------------------------------------------------------------- /overleaf-mcp-server.js: -------------------------------------------------------------------------------- ```javascript // Load project configuration const fs = require('fs'); const path = require('path'); let projectsConfig = {}; try { const projectsFile = fs.readFileSync(path.join(__dirname, 'projects.json'), 'utf8'); projectsConfig = JSON.parse(projectsFile); } catch (err) { // Ignore if projects.json file doesn't exist } const { Server } = require('@modelcontextprotocol/sdk/server/index.js'); const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js'); const { ListToolsRequestSchema, CallToolRequestSchema, } = require('@modelcontextprotocol/sdk/types.js'); const OverleafGitClient = require('./overleaf-git-client.js'); const server = new Server( { name: 'overleaf-mcp', version: '1.0.0' }, { capabilities: { tools: {} } } ); // Tools list server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: 'list_files', description: 'List all files in an Overleaf project', inputSchema: { type: 'object', properties: { extension: { type: 'string', description: 'File extension filter (e.g., .tex)', default: '.tex' }, projectName: { type: 'string', description: 'Project name (default, project2, etc.)' }, gitToken: { type: 'string', description: 'Git token (optional, uses env var)' }, projectId: { type: 'string', description: 'Project ID (optional, uses env var)' } }, additionalProperties: false } }, { name: 'read_file', description: 'Read a file from an Overleaf project', inputSchema: { type: 'object', properties: { filePath: { type: 'string', description: 'Path to the file' }, projectName: { type: 'string', description: 'Project name (default, project2, etc.)' }, gitToken: { type: 'string', description: 'Git token (optional, uses env var)' }, projectId: { type: 'string', description: 'Project ID (optional, uses env var)' } }, required: ['filePath'], additionalProperties: false } }, { name: 'get_sections', description: 'Get all sections from a LaTeX file', inputSchema: { type: 'object', properties: { filePath: { type: 'string', description: 'Path to the LaTeX file' }, projectName: { type: 'string', description: 'Project name (default, project2, etc.)' }, gitToken: { type: 'string', description: 'Git token (optional, uses env var)' }, projectId: { type: 'string', description: 'Project ID (optional, uses env var)' } }, required: ['filePath'], additionalProperties: false } }, { name: 'get_section_content', description: 'Get content of a specific section', inputSchema: { type: 'object', properties: { filePath: { type: 'string', description: 'Path to the LaTeX file' }, sectionTitle: { type: 'string', description: 'Title of the section' }, projectName: { type: 'string', description: 'Project name (default, project2, etc.)' }, gitToken: { type: 'string', description: 'Git token (optional, uses env var)' }, projectId: { type: 'string', description: 'Project ID (optional, uses env var)' } }, required: ['filePath', 'sectionTitle'], additionalProperties: false } }, { name: 'status_summary', description: 'Get a summary of the project status using default credentials', inputSchema: { type: 'object', properties: { projectName: { type: 'string', description: 'Project name (default, project2, etc.)' } }, additionalProperties: false } }, { name: 'list_projects', description: 'List all available projects', inputSchema: { type: 'object', properties: {}, additionalProperties: false } } ] }; }); // Tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { // Get project information function getProjectConfig(projectName) { if (projectName && projectsConfig.projects && projectsConfig.projects[projectName]) { return projectsConfig.projects[projectName]; } // Use 'default' project as fallback if (projectsConfig.projects && projectsConfig.projects.default) { return projectsConfig.projects.default; } throw new Error('No project configuration found. Please set up projects.json with at least a "default" project.'); } const projectConfig = getProjectConfig(args.projectName); const gitToken = args.gitToken || projectConfig.gitToken; const projectId = args.projectId || projectConfig.projectId; if (!gitToken || !projectId) { throw new Error('Git token and project ID are required. Set in projects.json or environment variables.'); } const client = new OverleafGitClient(gitToken, projectId); switch (name) { case 'list_files': const files = await client.listFiles(args.extension || '.tex'); return { content: [{ type: 'text', text: `Files found: ${files.length}\n\n${files.map(f => `• ${f}`).join('\n')}` }] }; case 'read_file': const content = await client.readFile(args.filePath); return { content: [{ type: 'text', text: `File: ${args.filePath}\nSize: ${content.length} characters\n\n${content}` }] }; case 'get_sections': const sections = await client.getSections(args.filePath); const sectionSummary = sections.map((s, i) => `${i + 1}. [${s.type}] ${s.title}\n Content preview: ${s.content.substring(0, 100).replace(/\s+/g, ' ')}...` ).join('\n\n'); return { content: [{ type: 'text', text: `Sections in ${args.filePath} (${sections.length} total):\n\n${sectionSummary}` }] }; case 'get_section_content': const section = await client.getSection(args.filePath, args.sectionTitle); if (!section) { throw new Error(`Section "${args.sectionTitle}" not found`); } return { content: [{ type: 'text', text: `Section: ${section.title}\nType: ${section.type}\nContent length: ${section.content.length} characters\n\n${section.content}` }] }; case 'list_projects': const projectList = Object.entries(projectsConfig.projects || {}).map(([key, project]) => `• ${key}: ${project.name} (${project.projectId})` ); return { content: [{ type: 'text', text: `Available Projects:\n\n${projectList.join('\n') || 'No projects configured in projects.json'}` }] }; case 'status_summary': // Project status summary const allFiles = await client.listFiles('.tex'); const projectName = projectConfig.name || 'Unknown Project'; let summary = `📄 ${projectName} Status Summary\n\n`; summary += `Project ID: ${projectId}\n`; summary += `Total .tex files: ${allFiles.length}\n`; summary += `Files: ${allFiles.join(', ')}\n\n`; if (allFiles.length > 0) { const mainFile = allFiles.find(f => f.includes('main')) || allFiles[0]; const sections = await client.getSections(mainFile); summary += `📋 Structure of ${mainFile}:\n`; summary += `Total sections: ${sections.length}\n\n`; sections.slice(0, 10).forEach((s, i) => { summary += `${i + 1}. [${s.type}] ${s.title}\n`; }); if (sections.length > 10) { summary += `... and ${sections.length - 10} more sections\n`; } } return { content: [{ type: 'text', text: summary }] }; default: throw new Error(`Unknown tool: ${name}`); } } catch (error) { return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true }; } }); // Start server async function main() { const transport = new StdioServerTransport(); await server.connect(transport); } main().catch(() => {}); ```