Skip to content
Back to search

emacs-mcp-server

Pure ELISP MCP server for Emacs

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/rhblind--emacs-mcp-server/badge.svg)](/listings/rhblind--emacs-mcp-server)

HTML

<a href="/listings/rhblind--emacs-mcp-server"><img src="/api/listings/rhblind--emacs-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Installation:** Place the files in your Emacs configuration directory and add to your config:

(add-to-list 'load-path "~/path-to/mcp-server")
(require 'mcp-server)

Alternatively, use package managers:

;; Using straight.el
(use-package mcp-server
  :straight (:type git :host github :repo "rhblind/emacs-mcp-server"
             :files ("*.el" "tools/*.el" "mcp-wrapper.py" "mcp-wrapper.sh"))
  :config
  (add-hook 'emacs-startup-hook #'mcp-server-start-unix))

;; Using use-package with manual path
(use-package mcp-server
  :load-path "~/path-to/mcp-server"
  :config
  (add-hook 'emacs-startup-hook #'mcp-server-start-unix))

;; Using Doom Emacs package! macro
(package! mcp-server
  :recipe (:type git :host github :repo "rhblind/emacs-mcp-server"
           :files ("*.el" "tools/*.el" "mcp-wrapper.py" "mcp-wrapper.sh")))

**Start the server:** Run `M-x mcp-server-start-unix` in Emacs. The server creates a Unix socket at `~/.config/emacs/.local/cache/emacs-mcp-server.sock`.

**Connect Claude Desktop:** Add this to your Claude Desktop configuration:

> [!NOTE] > Make sure you have `socat` installed!

{
  "mcpServers": {
    "emacs": {
      "command": "socat",
      "args": ["-", "UNIX-CONNECT:~/.config/emacs/.local/cache/emacs-mcp-server.sock"],
      "transport": "stdio"
    }
  }
}

**Connect Claude CLI**

claude mcp add emacs -- socat - UNIX-CONNECT:$HOME/.config/emacs/.local/cache/emacs-mcp-server.sock  # Uses socat directly
claude mcp add emacs ~/path-to/mcp-wrapper.py ~/.config/emacs/.local/cache/emacs-mcp-server.sock     # Uses the python wrapper script
claude mcp add emacs ~/path-to/mcp-wrapper.sh ~/.config/emacs/.local/cache/emacs-mcp-server.sock     # Uses the bash wrapper script

# Optionally, add to user scope so it's always available
claude mcp add emacs --scope user -- socat - UNIX-CONNECT:$HOME/.config/emacs/.local/cache/emacs-mcp-server.sock

Claude can now interact with your Emacs session.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 630 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MCP Server for Emacs
  2. [![Test Suite](https://github.com/rhblind/emacs-mcp-server/actions/workflows/test.yml/badge.svg)](https://github.com/rhblind/emacs-mcp-server/actions/workflows/test.yml)
  3. [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
  4. [![Emacs](https://img.shields.io/badge/Emacs-27.1+-purple)](https://www.gnu.org/software/emacs/)
  5. Connect Large Language Models directly to your Emacs environment! This MCP (Model Context Protocol) server exposes Emacs functionality through standardized tools,
  6. allowing LLMs like Claude to read and modify your buffers, execute elisp code, navigate files, and much more.
  7. <div align="center">
  8. <img src="./demo/change-theme-demo.gif" alt="Change Theme Demo" width="80%" />
  9. <br><br>
  10. <img src="./demo/write-poem-demo.gif" alt="Write Poem Demo" width="80%" />
  11. </div>
  12. ## Quick Start
  13. **Installation:** Place the files in your Emacs configuration directory and add to your config:
  14. ```elisp
  15. (add-to-list 'load-path "~/path-to/mcp-server")
  16. (require 'mcp-server)
  17. ```
  18. Alternatively, use package managers:
  19. ```elisp
  20. ;; Using straight.el
  21. (use-package mcp-server
  22. :straight (:type git :host github :repo "rhblind/emacs-mcp-server"
  23. :files ("*.el" "tools/*.el" "mcp-wrapper.py" "mcp-wrapper.sh"))
  24. :config
  25. (add-hook 'emacs-startup-hook #'mcp-server-start-unix))
  26. ;; Using use-package with manual path
  27. (use-package mcp-server
  28. :load-path "~/path-to/mcp-server"
  29. :config
  30. (add-hook 'emacs-startup-hook #'mcp-server-start-unix))
  31. ;; Using Doom Emacs package! macro
  32. (package! mcp-server
  33. :recipe (:type git :host github :repo "rhblind/emacs-mcp-server"
  34. :files ("*.el" "tools/*.el" "mcp-wrapper.py" "mcp-wrapper.sh")))
  35. ```
  36. **Start the server:** Run `M-x mcp-server-start-unix` in Emacs. The server creates a Unix socket at `~/.config/emacs/.local/cache/emacs-mcp-server.sock`.
  37. **Connect Claude Desktop:** Add this to your Claude Desktop configuration:
  38. > [!NOTE]
  39. > Make sure you have `socat` installed!
  40. ```json
  41. {
  42. "mcpServers": {
  43. "emacs": {
  44. "command": "socat",
  45. "args": ["-", "UNIX-CONNECT:~/.config/emacs/.local/cache/emacs-mcp-server.sock"],
  46. "transport": "stdio"
  47. }
  48. }
  49. }
  50. ```
  51. **Connect Claude CLI**
  52. ```bash
  53. claude mcp add emacs -- socat - UNIX-CONNECT:$HOME/.config/emacs/.local/cache/emacs-mcp-server.sock # Uses socat directly
  54. claude mcp add emacs ~/path-to/mcp-wrapper.py ~/.config/emacs/.local/cache/emacs-mcp-server.sock # Uses the python wrapper script
  55. claude mcp add emacs ~/path-to/mcp-wrapper.sh ~/.config/emacs/.local/cache/emacs-mcp-server.sock # Uses the bash wrapper script
  56. # Optionally, add to user scope so it's always available
  57. claude mcp add emacs --scope user -- socat - UNIX-CONNECT:$HOME/.config/emacs/.local/cache/emacs-mcp-server.sock
  58. ```
  59. Claude can now interact with your Emacs session.
  60. ## What LLMs Can Do
  61. Once connected, LLMs can perform powerful operations in your Emacs environment:
  62. **Code and Text Manipulation**
  63. - Read and write any buffer - get content from files, scratch buffers, terminals
  64. - Execute elisp code - run any Emacs Lisp expression safely
  65. - Navigate and edit - move cursor, insert text, select regions
  66. - Manage files - open, save, create new files and buffers
  67. **Emacs Integration**
  68. - Run interactive commands - execute any `M-x` command programmatically
  69. - Access variables - read and modify Emacs configuration and state
  70. - Window management - get layout information, manage splits
  71. - Major mode operations - work with mode-specific functionality
  72. ## Available Tools
  73. ### eval-elisp
  74. Executes an arbitrary Elisp expression in the running Emacs process and returns the printed result. The expression passes through the security layer, which blocks dangerous functions and credential-bearing files (see [Security](#security)).
  75. **Parameters:**
  76. | Parameter | Type | Required | Description |
  77. |--------------|--------|----------|-----------------------------------|
  78. | `expression` | string | Yes | The Elisp expression to evaluate. |
  79. **Example response:**
  80. ```json
  81. {
  82. "content": [
  83. {"type": "text", "text": "6"}
  84. ]
  85. }
  86. ```
  87. ### get-diagnostics
  88. Retrieves errors and warnings from flycheck or flymake (auto-detected per buffer) across all project buffers. Results are grouped by file and sorted by severity.
  89. **Parameters:**
  90. | Parameter | Type | Required | Description |
  91. |-------------|--------|----------|-----------------------------------------------|
  92. | `file_path` | string | No | Get diagnostics for a specific file only |
  93. | `severity` | string | No | Filter by `"error"`, `"warning"`, or `"info"` |
  94. **Example response:**
  95. ```json
  96. {
  97. "summary": {"total": 5, "errors": 2, "warnings": 3, "info": 0},
  98. "files": {
  99. "/path/to/file.el": {
  100. "error_count": 2,
  101. "warning_count": 1,
  102. "info_count": 0,
  103. "diagnostics": [
  104. {
  105. "line": 42,
  106. "column": 10,
  107. "message": "Unused variable 'foo'",
  108. "severity": "warning",
  109. "source": "emacs-lisp"
  110. }
  111. ]
  112. }
  113. }
  114. }
  115. ```
  116. ### Org-mode Tools
  117. The server ships 10 org-mode tools plus 3 org-roam-specific tools (the roam
  118. tools register only when `org-roam` is installed).
  119. **Read tools**
  120. - `org-agenda` - structured agenda and TODO views.
  121. - `org-search` - heading search using org's match syntax (`"+work-home/!TODO"` etc.).
  122. - `org-get-node` - fetch a heading or file body.
  123. - `org-list-templates` - enumerate the user's capture templates so the LLM
  124. can pick the right `template_key`.
  125. - `org-list-tags` - enumerate existing tags with usage counts so the LLM can
  126. prefer reusing an established tag over creating a near-duplicate.
  127. **Write tools**
  128. - `org-capture` - create a new entry; template mode respects the user's
  129. `org-capture-templates` verbatim.
  130. - `org-update-node` - update title, TODO state, priority, tags, properties,
  131. schedule, deadline, or body on an existing heading.
  132. - `org-refile` - move a heading under another.
  133. - `org-archive` - archive a heading to its configured archive target.
  134. - `org-clock` - clock in, out, or cancel.
  135. **Org-roam tools** (register only if `org-roam` is installed)
  136. - `org-roam-search` - find nodes by title, alias, tag, or ref.
  137. - `org-roam-get-node` - fetch a node with its backlinks.
  138. - `org-roam-capture` - create a new node, respecting
  139. `org-roam-capture-templates`.
  140. All write tools respect `mcp-server-emacs-tools-org-allowed-roots`, which
  141. defaults to directories containing `org-directory` and `org-agenda-files`.
  142. Writes auto-save the target buffer by default; set
  143. `mcp-server-emacs-tools-org-auto-save` to `nil` to manage saves manually.
  144. ## Configuration
  145. **Socket naming strategies:** Choose how sockets are named based on your setup:
  146. ```elisp
  147. (setq mcp-server-socket-name nil) ; Default: emacs-mcp-server.sock
  148. (setq mcp-server-socket-name 'user) ; User-based: emacs-mcp-server-{username}.sock
  149. (setq mcp-server-socket-name 'session) ; Session-based: emacs-mcp-server-{username}-{pid}.sock
  150. (setq mcp-server-socket-name "custom") ; Custom: emacs-mcp-server-custom.sock
  151. ```
  152. **Tool selection:** Choose which tools to enable:
  153. ```elisp
  154. ;; Enable all tools (default)
  155. (setq mcp-server-emacs-tools-enabled 'all)
  156. ;; Enable only specific tools (disable eval-elisp for security)
  157. (setq mcp-server-emacs-tools-enabled '(get-diagnostics))
  158. ;; Enable only eval-elisp
  159. (setq mcp-server-emacs-tools-enabled '(eval-elisp))
  160. ```
  161. **Other configuration options:**
  162. ```elisp
  163. ;; Custom socket directory
  164. (setq mcp-server-socket-directory "~/.config/emacs-mcp/")
  165. ;; Auto-start server when Emacs starts
  166. (add-hook 'emacs-startup-hook #'mcp-server-start-unix)
  167. ;; Enable debug logging
  168. (setq mcp-server-debug t)
  169. ```
  170. ## Security
  171. > [!WARNING]
  172. > The MCP server implements certain security measures to protect your Emacs environment and sensitive data from unauthorized access by LLMs.
  173. > However, the `eval-elisp` tool enables arbitrary evaluation of Elisp code in your Emacs process and therefore by definition enables remote code execution for the LLM.
  174. > **Use this tool with extreme caution!**
  175. ### Security Features
  176. **Permission System:**
  177. - **Dangerous function protection** - Functions like `delete-file`, `shell-command`, `find-file`, `write-file`, `make-network-process`, `make-process`, `async-shell-command`, `setenv` require user approval
  178. - **Sensitive file protection** - Automatic blocking of credential files (`.authinfo`, `.netrc`, SSH keys, etc.) for both reads and writes, even when the function itself is allowed
  179. - **Buffer access controls** - Protection for sensitive buffers like `*Messages*`, `*shell*`, `*terminal*`
  180. - **Permission caching** - Decisions are remembered for the session to avoid repeated prompts
  181. - **Audit logging** - Complete trail of all security events and decisions
  182. **Input Validation:**
  183. - **JSON Schema validation** - All tool inputs are validated against defined schemas
  184. - **Code injection protection** - Elisp expressions are scanned for dangerous patterns
  185. - **Path traversal prevention** - File paths are validated to prevent directory escape attacks
  186. - **Content scanning** - File contents are checked for credential patterns before access
  187. **Execution Limits:**
  188. - **Timeout protection** - Operations are limited to 30 seconds by default
  189. - **Memory monitoring** - Resource usage is tracked during execution
  190. - **Safe evaluation** - All Elisp code goes through security validation before execution
  191. ### Security Limitations
  192. The security model provides defense-in-depth but has known limitations:
  193. - **`let`-binding positions not fully checked** - The static form walker does not recurse into `let`/`let*` binding-value positions, so `(let ((x (shell-command "id"))) x)` bypasses the blocklist. Tracked in [#10](https://github.com/rhblind/emacs-mcp-server/issues/10).
  194. - **Dynamic function construction** - Code can construct function names at runtime to evade static analysis: `(funcall (intern "delete-file") "/tmp/test")` passes the checker. Tracked in [#10](https://github.com/rhblind/emacs-mcp-server/issues/10).
  195. - **Macro expansion** - The form walker operates on unexpanded forms. Macros that wrap dangerous calls in non-tail positions (other than `let` bindings) may not be caught.
  196. **This means:** Using `eval-elisp` requires trusting the LLM completely. The security controls reduce risk of accidental harm but cannot prevent a determined adversary.
  197. For higher security requirements, consider:
  198. 1. Restricting tool access via `mcp-server-emacs-tools-enabled`
  199. 2. Running Emacs in a sandboxed environment
  200. 3. Implementing an allowlist approach for truly critical systems
  201. ### Default Protected Files
  202. The server automatically protects these sensitive file patterns.
  203. Patterns starting with `~/` or `/` are matched as path prefixes after expanding `~`. Patterns containing `*` or `?` are treated as shell globs (e.g. `~/.authinfo*` matches `~/.authinfo`, `~/.authinfo.gpg`, `~/.authinfo.enc`, etc.). Bare filename patterns (no leading `~/`) match against the file's basename.
  204. **Authentication Files:**
  205. - `~/.authinfo` and variants - Emacs authentication data
  206. - `~/.netrc` and variants - Network authentication credentials
  207. - `~/.ssh/` - SSH keys and configuration (entire directory)
  208. - `~/.gnupg/` - GPG keys and configuration (entire directory)
  209. **Cloud & Service Credentials:**
  210. - `~/.aws/` - AWS credentials
  211. - `~/.docker/config.json` - Docker authentication
  212. - `~/.kube/config` - Kubernetes configuration
  213. - `~/.config/gh/` - GitHub CLI credentials
  214. **System Files:**
  215. - `/etc/passwd`, `/etc/shadow` - System authentication
  216. - `~/.password-store/` - Password manager data
  217. - Files containing "passwords", "secrets", "credentials", "keys", "tokens"
  218. ### Security Configuration
  219. The default settings aim for a reasonable balance between security and usability: the most commonly dangerous functions are blocked, well-known credential files are protected, and operations fail silently rather than prompting. These defaults will not suit every workflow. You are encouraged to review them and adjust to your own needs, for example by tightening the dangerous function list, adding project-specific sensitive file patterns, or enabling prompts instead of silent denial.
  220. Users have complete control over the security model through customizable settings:
  221. **Customize Sensitive Files:**
  222. ```elisp
  223. ;; Add your own sensitive file patterns.
  224. ;; Patterns starting with ~/ or / are matched as path prefixes (after expanding ~).
  225. ;; Patterns containing * or ? are treated as shell globs.
  226. ;; Bare filename patterns match against the file's basename.
  227. (setq mcp-server-security-sensitive-file-patterns
  228. '("~/.authinfo*" ; glob: matches .authinfo, .authinfo.gpg, .authinfo.enc, ...
  229. "~/.ssh/" ; prefix: matches everything under ~/.ssh/
  230. "~/my-secrets/" ; prefix: matches everything under ~/my-secrets/
  231. ".key")) ; basename: matches any file whose name contains ".key"
  232. ;; Allow specific sensitive files without prompting
  233. (setq mcp-server-security-allowed-sensitive-files
  234. '("~/.ssh/known_hosts" "~/safe-config.txt"))
  235. ```
  236. **Customize Dangerous Functions:**
  237. ```elisp
  238. ;; Modify which functions require permission
  239. (setq mcp-server-security-dangerous-functions
  240. '(delete-file shell-command find-file write-region))
  241. ;; Allow specific functions without prompting
  242. (setq mcp-server-security-allowed-dangerous-functions
  243. '(find-file dired)) ; Allow file browsing freely
  244. ```
  245. **Global Security Settings:**
  246. ```elisp
  247. ;; Block dangerous operations silently without prompting (default)
  248. (setq mcp-server-security-prompt-for-permissions nil)
  249. ;; Customize execution timeout
  250. (setq mcp-server-security-max-execution-time 60) ; 60 seconds
  251. ;; Add custom sensitive buffer patterns
  252. (setq mcp-server-security-sensitive-buffer-patterns
  253. '("*Messages*" "*shell*" "*my-secure-buffer*"))
  254. ```
  255. **Use Emacs Customize Interface:**
  256. ```elisp
  257. M-x customize-group RET mcp-server RET
  258. ```
  259. ### Security Modes
  260. **Paranoid Mode:**
  261. ```elisp
  262. ;; Very restrictive - prompts for everything
  263. (setq mcp-server-security-dangerous-functions
  264. '(find-file insert-file-contents switch-to-buffer eval load require))
  265. (setq mcp-server-security-allowed-dangerous-functions nil)
  266. (setq mcp-server-security-prompt-for-permissions t)
  267. ```
  268. **Permissive Mode:**
  269. ```elisp
  270. ;; More relaxed for trusted development scenarios
  271. (setq mcp-server-security-allowed-dangerous-functions
  272. '(find-file dired insert-file-contents))
  273. ;; Keep file protections for credentials
  274. (setq mcp-server-security-sensitive-file-patterns
  275. '("~/.authinfo*" "~/.netrc*" "~/.ssh/" "~/.gnupg/"))
  276. ```
  277. **Whitelist-Only Mode:**
  278. ```elisp
  279. ;; Only allow explicitly whitelisted operations
  280. (setq mcp-server-security-prompt-for-permissions nil) ; No prompts - just deny
  281. (setq mcp-server-security-allowed-dangerous-functions '(buffer-string point))
  282. (setq mcp-server-security-allowed-sensitive-files nil) ; No sensitive files allowed
  283. ```
  284. ### Monitoring Security
  285. **View Security Activity:**
  286. ```elisp
  287. M-x mcp-server-security-show-audit-log ; View all security events
  288. M-x mcp-server-security-show-permissions ; View cached permission decisions
  289. M-x mcp-server-security-clear-permissions ; Reset all cached permissions
  290. ```
  291. **Security Events Include:**
  292. - Permission requests (granted/denied)
  293. - Sensitive file access attempts
  294. - Dangerous function calls
  295. - Security configuration changes
  296. - Execution timeouts and errors
  297. ### Best Practices
  298. 1. **Keep defaults** - The default security settings provide good protection for most users
  299. 2. **Review audit logs** - Regularly check what the LLM has been trying to access
  300. 3. **Use whitelists** - For recurring workflows, whitelist specific safe operations
  301. 4. **Monitor credentials** - Be especially careful with any files containing passwords or API keys
  302. 5. **Test security** - Verify your configuration blocks unauthorized access as expected
  303. Operations requiring explicit permission include file system operations (`delete-file`, `write-region`, `write-file`, `append-to-file`, `copy-file`, `rename-file`, `with-temp-file`), process execution (`shell-command`, `call-process`, `start-process`), network access (`make-network-process`, `open-network-stream`, `url-retrieve`), directory enumeration (`directory-files`, `directory-files-recursively`), system functions (`kill-emacs`, `server-start`), and access to sensitive files or buffers.
  304. ## Management Commands
  305. **Server control:** `M-x mcp-server-start-unix` (start), `M-x mcp-server-stop` (stop), `M-x mcp-server-restart` (restart), `M-x mcp-server-status` (show status)
  306. **Debugging and monitoring:** `M-x mcp-server-toggle-debug` (toggle debug logging), `M-x mcp-server-list-clients` (show connected clients), `M-x mcp-server-get-socket-path` (show socket path)
  307. **Security management:** `M-x mcp-server-security-show-audit-log` (view security log), `M-x mcp-server-security-show-permissions` (view cached permissions)
  308. ## Client Integration
  309. ### Claude Desktop
  310. **Using shell wrapper (recommended):**
  311. ```json
  312. {
  313. "mcpServers": {
  314. "emacs": {
  315. "command": "/path/to/mcp-wrapper.sh",
  316. "args": ["$HOME/.emacs.d/.local/cache/emacs-mcp-server.sock"],
  317. "transport": "stdio"
  318. }
  319. }
  320. }
  321. ```
  322. **Using Python wrapper:**
  323. ```json
  324. {
  325. "mcpServers": {
  326. "emacs": {
  327. "command": "python3",
  328. "args": ["/path/to/mcp-wrapper.py", "$HOME/.emacs.d/.local/cache/emacs-mcp-server.sock"],
  329. "transport": "stdio"
  330. }
  331. }
  332. }
  333. ```
  334. **Direct socat (simple but less robust):**
  335. ```json
  336. {
  337. "mcpServers": {
  338. "emacs": {
  339. "command": "socat",
  340. "args": ["-", "UNIX-CONNECT:$HOME/.emacs.d/.local/cache/emacs-mcp-server.sock"],
  341. "transport": "stdio"
  342. }
  343. }
  344. }
  345. ```
  346. ### Wrapper Scripts
  347. **Shell wrapper (`mcp-wrapper.sh`)** - Lightweight, uses socat, good for simple integrations:
  348. ```bash
  349. ./mcp-wrapper.sh ~/.emacs.d/.local/cache/emacs-mcp-server.sock
  350. ./mcp-wrapper.sh /custom/path/emacs-mcp-server-myinstance.sock
  351. EMACS_MCP_DEBUG=1 ./mcp-wrapper.sh ~/.emacs.d/.local/cache/emacs-mcp-server.sock
  352. ```
  353. **Python wrapper (`mcp-wrapper.py`)** - More robust error handling, better cross-platform support:
  354. ```bash
  355. ./mcp-wrapper.py ~/.emacs.d/.local/cache/emacs-mcp-server.sock
  356. ./mcp-wrapper.py --list-sockets
  357. EMACS_MCP_DEBUG=1 ./mcp-wrapper.py ~/.emacs.d/.local/cache/emacs-mcp-server.sock
  358. ```
  359. **Environment variables** for both wrappers:
  360. - `EMACS_MCP_TIMEOUT`: Connection timeout in seconds (default: 10)
  361. - `EMACS_MCP_DEBUG`: Enable debug logging
  362. ### Custom MCP Client
  363. For your own MCP client implementation:
  364. ```python
  365. import socket
  366. import json
  367. # Connect to Emacs MCP Server
  368. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  369. sock.connect("~/.emacs.d/.local/cache/emacs-mcp-server.sock")
  370. # Send initialization
  371. init_msg = {
  372. "jsonrpc": "2.0",
  373. "id": 1,
  374. "method": "initialize",
  375. "params": {
  376. "protocolVersion": "draft",
  377. "capabilities": {},
  378. "clientInfo": {"name": "my-client", "version": "1.0.0"}
  379. }
  380. }
  381. sock.send((json.dumps(init_msg) + "\n").encode())
  382. response = sock.recv(4096).decode()
  383. print(response)
  384. ```
  385. ## Testing and Development
  386. **Quick test:** Run `./test/scripts/test-runner.sh` or test a specific socket with `./test/integration/test-unix-socket-fixed.sh ~/.emacs.d/.local/cache/emacs-mcp-server.sock`
  387. **Adding custom tools:**
  388. Create a new file in the `tools/` directory:
  389. ```elisp
  390. ;;; tools/mcp-server-emacs-tools-my-tool.el
  391. (require 'mcp-server-tools)
  392. (defun mcp-server-emacs-tools--my-tool-handler (args)
  393. "Handle my-tool invocation with ARGS."
  394. (let ((param (alist-get 'param args)))
  395. (format "Result: %s" param)))
  396. (mcp-server-register-tool
  397. (make-mcp-server-tool
  398. :name "my-tool"
  399. :title "My Custom Tool"
  400. :description "Description of what this tool does"
  401. :input-schema '((type . "object")
  402. (properties . ((param . ((type . "string")
  403. (description . "A parameter")))))
  404. (required . ["param"]))
  405. :function #'mcp-server-emacs-tools--my-tool-handler))
  406. (provide 'mcp-server-emacs-tools-my-tool)
  407. ```
  408. Then register it in `mcp-server-emacs-tools.el`:
  409. ```elisp
  410. ;; Add to mcp-server-emacs-tools--available alist:
  411. (defconst mcp-server-emacs-tools--available
  412. '((eval-elisp . mcp-server-emacs-tools-eval-elisp)
  413. (get-diagnostics . mcp-server-emacs-tools-diagnostics)
  414. (my-tool . mcp-server-emacs-tools-my-tool)) ; Add your tool here
  415. "Alist mapping tool names (symbols) to their feature names.")
  416. ```
  417. The tool will self-register when loaded. Use `mcp-server-emacs-tools-enabled` to control which tools are exposed to LLM clients.
  418. ## Troubleshooting
  419. **Server won't start:**
  420. - Check if socket directory exists and is writable, verify no other server is using the same socket path, check Emacs *Messages* buffer for error details.
  421. **Socket not found:**
  422. - Check if Emacs MCP Server is running: `M-x mcp-server-status`
  423. - Verify socket path: `M-x mcp-server-get-socket-path`
  424. - List available sockets: `./mcp-wrapper.sh --list-sockets`
  425. **Connection refused:**
  426. - Check socket permissions: `ls -la ~/.emacs.d/.local/cache/emacs-mcp-server*.sock`
  427. - Test socket connectivity: `echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | socat - UNIX-CONNECT:~/.emacs.d/.local/cache/emacs-mcp-server.sock`
  428. **MCP client issues:**
  429. - Verify client configuration: Check JSON syntax and file paths
  430. - Check client logs: Most MCP clients provide debug logging
  431. - Test wrapper independently: Run wrapper script manually to verify connection
  432. **Permission errors:**
  433. - View audit log with `M-x mcp-server-security-show-audit-log`, grant specific permissions with `(mcp-server-security-grant-permission 'function-name)`, or disable prompting with `(mcp-server-security-set-prompting nil)`.
  434. **Debug mode:**
  435. - Enable with `(setq mcp-server-debug t)` or toggle with `M-x mcp-server-toggle-debug`.
  436. ## Advanced Configuration
  437. **Multiple Emacs instances:**
  438. ```elisp
  439. ;; Instance 1
  440. (setq mcp-server-socket-name "instance-1")
  441. (mcp-server-start-unix)
  442. ;; Instance 2
  443. (setq mcp-server-socket-name "instance-2")
  444. (mcp-server-start-unix)
  445. ```
  446. **Dynamic socket naming:**
  447. ```elisp
  448. (setq mcp-server-socket-name
  449. (lambda ()
  450. (format "emacs-%s-%d" (system-name) (emacs-pid))))
  451. ```
  452. **Performance tips:**
  453. - Use predictable naming to avoid socket discovery overhead
  454. - Keep connections alive and reuse when possible
  455. - Monitor clients with `M-x mcp-server-list-clients`
  456. - Stop unused servers to free resources
  457. ## Architecture
  458. The server uses a modular design with a transport layer (Unix domain sockets), protocol layer (JSON-RPC 2.0 message handling), tool registry (Elisp functions exposed as MCP tools), and security layer (permission management and validation).
  459. ```mermaid
  460. flowchart LR
  461. subgraph Client
  462. LLM[LLM Client<br/>Claude Desktop/CLI]
  463. end
  464. subgraph Bridge
  465. Wrapper[mcp-wrapper<br/>stdio ↔ socket]
  466. end
  467. subgraph Emacs
  468. subgraph Transport
  469. Socket[Unix Socket<br/>Transport]
  470. end
  471. spacer[ ]
  472. style spacer fill:none,stroke:none
  473. subgraph MCP["MCP Server"]
  474. Protocol[Protocol Layer<br/>JSON-RPC 2.0]
  475. Security[Security Layer<br/>Permissions]
  476. Tools[Tool Registry]
  477. end
  478. Elisp[Emacs Lisp<br/>Runtime]
  479. end
  480. LLM <-->|stdio| Wrapper
  481. Wrapper <-->|Unix Socket| Socket
  482. Socket <-->|Messages| Protocol
  483. Protocol --> Security
  484. Security --> Tools
  485. Tools --> Elisp
  486. Elisp -->|Result| Protocol
  487. ```
  488. ## License
  489. This program is free software; you can redistribute it and/or modify it under the terms of the [GNU General Public License](https://www.gnu.org/licenses/gpl-3.0.txt) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.