latex-mcp
# latex-mcp
`latex-mcp` is a local, reusable [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for safely inspecting, editing, searching, compiling, and diagnosing a single LaTeX project directory. It is designed as a foundation for academic, research, technical, and personal LaTeX workflows.
This server works only with local files. It does **not** connect to Overleaf, use browser automation, use Overleaf Git integration, or deploy remotely. Optional Auth0 token validation is available for local Streamable HTTP architecture testing; it does not make the server safe to expose publicly.
## Status
Working prototype. Verified end to end through Claude as a remote custom connector (Streamable HTTP + Auth0 OAuth, via a temporary Cloudflare Quick Tunnel): `list_files`, `read_file`, `write_file` and `compile_latex` (pdflatex). The other tools are covered by the automated tests. It is **not** production-ready: see [Known limitations and future work](#known-limitations-and-future-work).
For Claude Desktop on the same machine, the default stdio transport needs no tunnel and no OAuth.
## Architecture
```text
MCP host (for example, Claude)
|
v
latex-mcp server (stdio)
|-- ProjectFileSystem: bounded project-relative text file operations
|-- ProjectSandbox: containment and symlink escape checks
`-- LaTeXCompiler: allowlisted TeX engines and diagnostic extraction
|
`-- configured local LaTeX project + installed TeX distribution
```
The server uses the official MCP Python SDK **2.1.1** (`mcp==2.1.1`) and its v2 `MCPServer` API. Python 3.11 or newer is required.
## Installation
Create and activate a virtual environment, then install the project and its development dependencies:
```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
```
On macOS or Linux, activate with `source .venv/bin/activate`.
## Configure and run
Set `LATEX_PROJECT_ROOT` to the directory of the LaTeX project you want this one server instance to manage. The path is deliberately not stored in source code.
### Stdio (default)
Stdio is the default transport and is intended for a local MCP host that launches `latex-mcp` as a subprocess.
```powershell
$env:LATEX_PROJECT_ROOT = "C:\path\to\your\latex-project"
$env:LATEX_MCP_TRANSPORT = "stdio" # optional: stdio is the default
latex-mcp
```
The process uses standard input/output for MCP communication; do not write ordinary log messages to stdout. A host such as Claude can later be configured to launch that command with `LATEX_PROJECT_ROOT` in its environment.
### Streamable HTTP (local development only)
For local testing, select the SDK's Streamable HTTP transport. The server accepts only loopback hosts (`127.0.0.1`, `localhost`, or `::1`) and defaults to `http://127.0.0.1:8000/mcp`.
```powershell
$env:LATEX_PROJECT_ROOT = "C:\path\to\your\latex-project"
$env:LATEX_MCP_TRANSPORT = "streamable-http"
$env:LATEX_MCP_HTTP_HOST = "127.0.0.1" # loopback only
$env:LATEX_MCP_HTTP_PORT = "8000" # optional
$env:LATEX_MCP_HTTP_PATH = "/mcp" # optional
latex-mcp
```
The Streamable HTTP endpoint validates `Host` and `Origin` headers with DNS-rebinding protection always enabled. Local defaults allow only `127.0.0.1`, `localhost`, and `::1`. These comma-separated environment variables can narrow the accepted local values when needed:
```powershell
$env:LATEX_MCP_HTTP_ALLOWED_HOSTS = "127.0.0.1:*"
$env:LATEX_MCP_HTTP_ALLOWED_ORIGINS = "http://127.0.0.1:*"
```
Only loopback hosts and `http://` loopback origins are accepted by this MVP; the protection cannot be disabled. HTTP requests are limited to 2,500,000 bytes by default (`LATEX_MCP_HTTP_MAX_REQUEST_BODY_BYTES`, maximum 8,000,000 bytes), and at most eight tool calls run concurrently (`LATEX_MCP_MAX_CONCURRENT_TOOL_CALLS`).
**Do not expose local HTTP mode publicly.** It is deliberately limited to loopback binding and is suitable only for local architecture and connector testing. Authentication does not replace HTTPS, a reverse proxy, deployment hardening, operational monitoring, or a public-network security review.
### Local Auth0 resource-server testing
HTTP authentication is opt-in and applies only to Streamable HTTP. Stdio remains unauthenticated and unchanged. The server is an OAuth resource server only: it validates access tokens issued by Auth0; it does not host login pages, issue tokens, or implement client registration.
```powershell
$env:LATEX_PROJECT_ROOT = "C:\path\to\your\latex-project"
$env:LATEX_MCP_TRANSPORT = "streamable-http"
$env:LATEX_MCP_HTTP_HOST = "127.0.0.1"
$env:LATEX_MCP_HTTP_AUTHENTICATION = "auth0"
$env:LATEX_MCP_AUTH0_ISSUER_URL = "https://YOUR_TENANT.us.auth0.com/"
$env:LATEX_MCP_AUTH0_RESOURCE_SERVER_URL = "http://127.0.0.1:8000/mcp"
latex-mcp
```
`LATEX_MCP_AUTH0_RESOURCE_SERVER_URL` is Auth0's API identifier and the required JWT audience. In local mode it can also be the loopback MCP URL above. When `LATEX_MCP_PUBLIC_URL` is set, protected-resource metadata instead advertises the externally reachable `${LATEX_MCP_PUBLIC_URL}${LATEX_MCP_HTTP_PATH}` endpoint, while access tokens continue to be checked against the stable Auth0 API identifier. `LATEX_MCP_AUTH0_JWKS_CACHE_SECONDS` controls successful Auth0 JWKS cache lifetime and defaults to `300` (allowed range: 1–86400).
No Auth0 client secret, access token, or signing key belongs in this server's configuration. Auth0 must be configured separately for Authorization Code + PKCE S256, an RS256 signing key, the Claude callback URI, and the canonical resource identifier. Auth0's Resource Parameter Compatibility Profile must be enabled so MCP's RFC 8707 `resource` parameter becomes the access-token audience.
Authenticated HTTP requests require an Auth0 RS256 JWT with a valid signature, issuer, expiry, audience/resource, and tool scope. The server retrieves public signing keys from the configured issuer's `/.well-known/jwks.json` endpoint and never accepts a caller-supplied JWKS location.
| Scope | Tools |
| --- | --- |
| `latex:read` | `list_files`, `read_file`, `search_files`, `get_compile_errors` |
| `latex:write` | `write_file`, `create_file`, `delete_file` |
| `latex:compile` | `compile_latex` |
Unauthenticated or invalid HTTP requests receive the MCP SDK's OAuth `401` Bearer challenge and RFC 9728 protected-resource metadata at `/.well-known/oauth-protected-resource/mcp` (or the equivalent path for a custom MCP endpoint). A valid token without a tool's required scope is refused before the filesystem or compiler operation begins.
### Connecting Claude as a remote custom connector
Notes from a working setup (Claude Desktop custom connector, Auth0, Cloudflare Quick Tunnel). Claude's servers, not your machine, call the public URL.
1. Run the tunnel and the server, with `LATEX_MCP_PUBLIC_URL` set to the tunnel's `https://` origin (no `/mcp`).
2. Claude sends the MCP URL (`<public URL>/mcp`) as the RFC 8707 `resource` parameter. In Auth0 the **API identifier must equal that exact URL**, and `LATEX_MCP_AUTH0_RESOURCE_SERVER_URL` must be set to the same value. A mismatch fails at Auth0 with `Service not found`.
3. With RBAC enabled, the signed-in user needs a **role that includes the API's three permissions**. Authorizing the application alone is not enough; without the role the token lacks the scopes.
4. Currently every HTTP request must carry all three scopes (`latex:read`, `latex:write`, `latex:compile`); otherwise the SDK answers `403`. A read-only token cannot connect.
5. Register `https://claude.ai/api/mcp/auth_callback` as the allowed callback for a Native (public) Auth0 application, and leave the client secret blank in Claude.
6. A Quick Tunnel URL changes on every restart, so steps 1-2 and the connector must be redone each time. Use a stable hostname for anything longer-lived.
7. Request logging is hidden by default. Set `LATEX_MCP_LOG_LEVEL=info` to see request lines while debugging.
### Dedicated workspace restriction
Set `LATEX_WORKSPACE_ROOT` to restrict project selection to an existing dedicated workspace. When set, `LATEX_PROJECT_ROOT` must resolve below it, including after symlink resolution.
```powershell
$env:LATEX_WORKSPACE_ROOT = "C:\latex-workspace"
$env:LATEX_PROJECT_ROOT = "C:\latex-workspace\project-a"
```
For development, the official MCP Inspector can run the entry point after installation:
```powershell
mcp dev src/latex_mcp/server.py
```
## MCP tools
| Tool | Purpose |
| --- | --- |
| `list_files(directory=".", recursive=false)` | List relative file and directory paths. |
| `read_file(path)` | Read one bounded UTF-8 text file. |
| `write_file(path, content)` | Replace an existing file. |
| `create_file(path, content)` | Create a new file; never overwrite. |
| `delete_file(path)` | Delete one file only; never a directory or project root. |
| `search_files(query, extensions=None)` | Find matching text lines, optionally filtered by extension. |
| `compile_latex(compiler_name="pdflatex", main_file=None)` | Compile with `pdflatex`, `xelatex`, or `lualatex`. |
| `get_compile_errors()` | Extract common errors and warnings from the latest compilation or log. |
Every tool returns a predictable envelope: `{ "ok": true, "result": ... }` on success or `{ "ok": false, "error": { "code": ..., "message": ... } }` for expected failures.
Common LaTeX text files such as `.tex`, `.bib`, `.cls`, `.sty`, `.bst`, `.cfg`, `.txt`, and `.md` work naturally. Rather than rely on a narrow extension allowlist, text operations safely reject binary and non-UTF-8 content.
## Compilation
`compile_latex` runs the chosen installed engine from the project root using a fixed argument array:
```text
<allowlisted-engine> -interaction=nonstopmode -halt-on-error -file-line-error -no-shell-escape <relative-main-file>
```
The tool never accepts a shell command. If `main_file` is omitted, it prefers `main.tex`; otherwise it will use exactly one discovered `.tex` file containing `\documentclass`, or ask for an explicit file. The compiler has a 120-second default timeout (configurable only from 1 to 300 seconds), captures bounded stdout/stderr, and permits one active compilation by default. `LATEX_MCP_MAX_CONCURRENT_COMPILATIONS` and `LATEX_MCP_COMPILE_QUEUE_TIMEOUT_SECONDS` control the local compilation slots; the queue timeout defaults to zero, so excess requests fail immediately. Builds write normal LaTeX artifacts within the configured project.
`get_compile_errors` recognizes common undefined-control-sequence, missing-file/package, reference/citation, box, and fatal-compilation diagnostics. It is deliberately a structured extractor rather than an AI log parser.
## Security model
The security boundary is the resolved `LATEX_PROJECT_ROOT`.
- All tool paths must be relative; POSIX absolute paths, Windows drive-qualified paths, null bytes, and `..` traversal are rejected.
- Requested paths are resolved and verified to remain under the project root.
- Symlinks that resolve outside the root are rejected and omitted from listings/searches.
- Reads, writes, search scans, search results, HTTP request bodies, compiler output, tool concurrency, and compile time have conservative limits.
- File deletion is single-file only; the project root and directories cannot be deleted.
- Compilation uses only a fixed TeX-engine allowlist, `shell=False`, no client-supplied arguments, and `-no-shell-escape`.
- Streamable HTTP uses explicit loopback-only Host/Origin allowlists with DNS-rebinding protection enabled.
- Optional Streamable HTTP authentication uses Auth0-issued RS256 access tokens, JWKS signature validation, issuer/audience/expiry checks, and per-tool scopes. It does not apply to stdio.
- Expected errors contain project-relative context only and avoid host-specific paths.
This server protects its MCP boundary; it cannot defend against a separate local process with permission to modify the configured project concurrently.
## Testing
Run the suite with:
```powershell
python -m pytest
```
Tests use temporary projects and cover core file operations, path traversal, absolute paths, Windows-style traversal, symlink escape, root deletion, compiler command allowlisting, tool registration, successful compilation, and compilation failures. Compiler tests skip cleanly when `pdflatex` is unavailable.
## Known limitations and future work
- The server manages one configured local project per process; it has no project profiles or multi-project routing.
- It does not run `latexmk`, inspect PDFs, validate bibliographies, or analyze auxiliary files beyond basic log diagnostics.
- `write_file` stores content exactly as the client sends it (UTF-8, no line-ending conversion). Clients that send LF will change CRLF files to LF, which can show as a whole-file diff.
- Over HTTP all three scopes are currently required on every request, so per-scope access (for example read-only) is not yet usable.
- No backups, Git integration, public endpoint, deployment, OAuth authorization server, OAuth login pages, DCR, or Overleaf synchronization are included.
Possible future additions include optional `latexmk` support, PDF inspection, reference/bibliography validation, project structure checks, backups, Git history, multiple profiles, authentication, remote transports, and opt-in Overleaf synchronization. Those features should preserve this project-root sandbox as their security boundary.
TDQS
Scored across 8 tools
Each tool has a clearly distinct file or LaTeX-build operation. The create_file/write_file boundary is explicitly documented, and list/read/delete/search/compile/error tools are unambiguous.
All tools follow a consistent snake_case verb_noun pattern, such as list_files, read_file, write_file, and compile_latex. No mixed casing or vague verb-only names appear.
Eight tools are well scoped for a LaTeX project file and compilation server. Each tool covers a necessary operation without redundant variants.
The surface covers file listing, reading, creation, replacement, deletion, and searching, plus LaTeX compilation and structured error extraction. This provides complete lifecycle coverage for the stated purpose with no obvious dead ends.