emacs-introspection-mcp

ElleNajt/emacs-introspection-mcp

3.3

If you are the rightful owner of emacs-introspection-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

A simple MCP server for Emacs introspection through the emacsclient daemon.

Tools
3
Resources
0
Prompts
0

#+title: Emacs Introspection MCP Server

A comprehensive MCP server for Emacs introspection through the emacsclient daemon. This server provides tools for exploring Emacs functions, variables, buffers, keymaps, and more.

  • Available Tools

** Meta-Tools (Recommended for AI Agents)

  • emacs_describe - Get comprehensive documentation for any Emacs symbol (function, variable, or both). Handles Lisp-2 namespace correctly with optional type parameter
  • emacs_search - Search for symbols with pattern matching and type filtering (commands, functions, variables, or all)
  • emacs_buffer_info - Complete buffer analysis including content, modes, variables, and metadata (outputs to file)
  • emacs_keymap_analysis - Analyze major and minor mode keymaps for a buffer context (outputs to file)

** Core Introspection Tools

  • get_variable_value - Get current value of any Emacs variable (e.g., emacs-version, tab-width)
  • get_buffer_list - Get list of all live buffers with optional detailed information

** Buffer Operations

  • view_buffer - Get buffer contents with line numbers (outputs to file)
  • open_file - Open a file in Emacs in background and return buffer name (restricted to current working directory and /tmp/ClaudeWorkingFolder)

** Workspace Management

  • get_workspace_buffers - Get list of buffers in each workspace (outputs to file)
  • create_workspace - Create a new workspace with given name
  • rename_workspace - Rename a workspace by name or identifier
  • delete_workspace - Delete a workspace by name or identifier
  • move_buffer_to_workspace - Move a buffer to a specific workspace (works with both Doom workspaces and Eyebrowse)

** Syntax & Code Analysis

  • check_parens - Validate parentheses balance in Lisp code files (opens fresh from disk, restricted to current working directory and /tmp/ClaudeWorkingFolder)

** Org Mode Integration

  • get_agenda - Retrieve org-agenda view with customizable agenda type (outputs to file)
  • org_get_all_todos - Get all TODO items from org files, including unscheduled ones (outputs to file)
  • org_schedule_todo - Schedule a TODO item by adding SCHEDULED property to headings
  • org_agenda_todo - Change the state of agenda items (TODO → DONE, etc.) by line number or heading text
  • org_archive_todo - Archive completed TODO items by moving them to archive files
  • org_agenda_goto - Navigate to source location of agenda items with context
  • org_capture - Add new items via org-capture with immediate completion (default) or buffer editing
  • Security & Safety

I've made some attempt to make this more secure against code injection, but none of this should be taken as any kind of guarantee.

** Comprehensive Input Sanitization All MCP tools are wrapped with a security decorator that provides multi-layer protection:

*** Input Validation

  • Pattern Detection: Automatically rejects inputs containing dangerous patterns like shell commands, elisp injection attempts, and malicious functions
  • Type Validation: Enforces proper data types and non-empty strings where required
  • Symbol Validation: Strict regex validation for Emacs symbols: /^[a-zA-Z][a-zA-Z0-9\-_:+*/?<>=!]*$/

*** File Path Security

  • Directory Restrictions: File operations limited to current working directory and /tmp/ClaudeWorkingFolder only
  • Path Traversal Prevention: Blocks ../ and ..\\ sequences in all file paths
  • Injection Protection: Rejects paths containing dangerous characters: quotes, semicolons, parentheses, shell metacharacters
  • Platform Safety: Prevents Windows-style absolute paths on Unix systems (which become relative and bypass restrictions)

*** Elisp Injection Prevention

  • Safe Quoting: Uses single quotes (') to prevent evaluation, unlike backtick which would be vulnerable to comma escaping
  • String Escaping: Proper escaping of backslashes, quotes, newlines, and control characters in elisp strings
  • Process Isolation: Uses execFile with shell=false to prevent shell injection attacks
  • Parameter Sanitization: All user inputs are validated and escaped before being inserted into elisp code

*** Attack Mitigation The security system prevents common attack vectors:

  • Code Injection: Elisp, shell command, and script injection attempts
  • Path Traversal: Directory escape attempts and unauthorized file access
  • Data Exfiltration: Unauthorized file system access outside allowed directories

** Risk Assessment File access is limited to safe directories, significantly reducing exfiltration risks compared to unbounded file system access. However, note that the ability to read open buffers in Emacs may provide Claude with more information than you are comfortable with, and if you give Claude unlimited access to the web then you may be in danger of exfiltration attacks ([[https://simonwillison.net/tags/lethal-trifecta/][Lethal Trifecta]]).

  • Installation ** Claude Code

To add this MCP server to Claude Code CLI:

#+begin_src bash claude mcp add -s user emacs-introspection npx @lnajt/emacs-introspection-mcp #+end_src

*** Configuration

The view_buffer and get_agenda functions write temporary files to /tmp/ClaudeWorkingFolder/. You need to add this directory to your Claude Code settings to allow access.

Add the following to your ~/.claude/settings.json under permissions.

#+begin_src json { "additionalDirectories": ["/tmp/ClaudeWorkingFolder"] } #+end_src

You can then use Claude Code with Emacs introspection capabilities:

  • Ask about Emacs functions: "What does the save-buffer function do?"
  • Get variable values: "What buffers are currently open in Emacs?"
  • View buffer contents: "Show me the contents of my scratch buffer"
  • Analyze buffer context: "What keybindings are available in my current buffer?"
  • Check your org agenda: "What's on my agenda today?"
  • Manage org tasks: "Add a new todo item", "Mark my first agenda item as done", or "Schedule this task for tomorrow"
  • Get all todos: "Show me all my TODO items across all org files"
  • Explore Emacs symbols: "Find all commands related to 'save'"
  • Organize workspaces: "Clean up my workspaces and reorganize buffers by project"

** Gptel

First, set up [[https://github.com/karthink/gptel][gptel]] and [[https://github.com/lizqwerscott/mcp.el][mcp.el]] .

Then, add this to your the mcp-hub-servers variable:

#+begin_src emacs-lisp :tangle yes ("emacs_introspection" . (:command "npx" :args ("-y" "@lnajt/emacs-introspection-mcp")) ) #+end_src

  • Recommended Usage

** For AI Agents The meta-tools are specifically designed for optimal AI agent experience:

  • emacs_describe - Provides comprehensive symbol documentation with proper Lisp-2 namespace handling
  • emacs_search - Unified search interface with type filtering for efficient symbol discovery
  • emacs_buffer_info - Complete buffer context including modes, variables, and content
  • emacs_keymap_analysis - Contextual keymap information for understanding available commands

** Common Workflows

  1. Exploring Unknown Codebase: emacs_buffer_infoemacs_searchemacs_describe
  2. Understanding Functions: emacs_searchemacs_describe (with key bindings)
  3. Buffer Investigation: get_buffer_listemacs_buffer_infoview_buffer
  4. Workflow Analysis: get_agendaorg_get_all_todosemacs_buffer_info for org files
  5. Task Management: org_get_all_todosorg_schedule_todoorg_agenda_todoorg_capture
  6. Buffer Reorganization: get_workspace_buffersget_buffer_listcreate_workspacemove_buffer_to_workspacedelete_workspace

** File Output Benefits Large results are written to /tmp/ClaudeWorkingFolder/ enabling:

  • Analysis of extensive data without token limits
  • Further processing with other tools
  • Persistent reference during conversation

** Buffer Reorganization Example A complete workflow to reorganize scattered buffers into project-specific workspaces:

#+begin_example

1. Assess current state

get_workspace_buffers() # See all buffers across workspaces get_buffer_list(true) # Get detailed buffer list with file paths

2. Create project workspaces

create_workspace("Frontend") # Web development files create_workspace("Backend") # Server-side code create_workspace("Config") # Configuration files create_workspace("Docs") # Documentation and notes

3. Organize by project type

move_buffer_to_workspace("package.json", "Frontend") move_buffer_to_workspace("src/components/App.jsx", "Frontend") move_buffer_to_workspace("styles/main.css", "Frontend")

move_buffer_to_workspace("server.py", "Backend") move_buffer_to_workspace("models/user.py", "Backend") move_buffer_to_workspace("database/schema.sql", "Backend")

move_buffer_to_workspace("init.el", "Config") move_buffer_to_workspace(".vimrc", "Config") move_buffer_to_workspace("config.yaml", "Config")

move_buffer_to_workspace("README.md", "Docs") move_buffer_to_workspace("Help", "Docs") move_buffer_to_workspace("todo.org", "Docs")

4. Clean up

delete_workspace("old-mixed-workspace") get_workspace_buffers() # Verify final organization #+end_example

** Comprehensive Task Management Example A complete workflow to review, organize, and manage org-mode tasks:

#+begin_example

1. Review current state

get_agenda() # See today's scheduled items org_get_all_todos() # Get all TODO items including unscheduled

2. Schedule unscheduled tasks

org_schedule_todo("/Documents/Notes/inbox.org", "Review project proposal", "today") org_schedule_todo("/Documents/Notes/tasks.org", "Call dentist", "+2d") org_schedule_todo("~/Documents/Notes/work.org", "Prepare presentation", "2025-01-20 09:00")

3. Update task states

org_agenda_todo("agenda_line", "3", "DONE") # Mark agenda line 3 as done org_agenda_todo("org_heading", "Buy groceries", "WAITING", org_file="~/Documents/Notes/personal.org") # Change specific heading

4. Add new tasks via capture

org_capture() # Show available templates org_capture("t", "Follow up on meeting notes") # Quick task capture org_capture("n", "Ideas for weekend project", false) # Open capture buffer for editing

5. Final review

get_agenda() # Check updated agenda org_get_all_todos() # Verify all tasks are properly organized #+end_example

  • LSP Support

LSP tools (eglot_help_at_point, eglot_find_definition, eglot_find_references) are available in /src/eglot-tools.ts but currently not working. They require proper eglot configuration and will be integrated when LSP support is functional.

  • Implementation Details

** Security Implementation All tools use comprehensive security measures including:

  • Security Decorator Pattern: Every MCP tool wrapped with input validation and sanitization
  • Multi-Layer Validation: Pattern detection, type checking, length limits, and character restrictions
  • Safe Elisp Generation: Proper escaping and quoting to prevent code injection
  • File System Restrictions: Strict directory limitations with path traversal protection
  • Process Isolation: Shell-free execution to prevent command injection

** File Output Large data (buffers, keymaps, agenda) is written to /tmp/ClaudeWorkingFolder/ to handle size limitations and enable further analysis with other tools.

** Core Functions The server implements the following elisp operations:

  • Symbol Documentation: (describe-function) and (describe-variable) with comprehensive Help buffer output
  • Variable Values: (symbol-value 'symbol)
  • Buffer Lists: (buffer-list) with optional detailed buffer information including file paths, sizes, and modification status
  • Buffer Content: (with-current-buffer "name" (buffer-string)) with line numbering and metadata
  • Symbol Search: Unified interface to apropos-* functions with type filtering (commands, functions, variables, all)
  • Buffer Analysis: Complete mode, variable, and content introspection with mode descriptions
  • Keymap Analysis: Major and minor mode keymap exploration with comprehensive key binding analysis
  • Syntax Checking: check-parens integration for Lisp code validation with precise error location reporting
  • File Operations: Background file opening with find-file-noselect and buffer name return
  • Org Integration: Agenda view extraction, comprehensive todo retrieval, scheduling, state management, and item capture with immediate completion

** Testing All tools have been tested and verified working with:

  • Emacs 30.1 - Full compatibility testing
  • Security Validation - Comprehensive test suite with 42 passing tests covering injection prevention, path traversal protection, and input sanitization
  • Core Functionality - Basic connection, variable retrieval, buffer operations, and error handling
  • Advanced Features - Symbol search, documentation, meta-tools analysis, org agenda integration, and syntax checking
  • Edge Cases - Unicode handling, long paths, special characters, and malformed inputs

For detailed testing instructions and security validation, see TESTING.md.