-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathemacs-mcp-server.js
More file actions
executable file
·268 lines (245 loc) · 7.77 KB
/
emacs-mcp-server.js
File metadata and controls
executable file
·268 lines (245 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env node
// WARNING: This file was generated via ampcode.com by a person not proficient in JavaScript.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { execSync } from "node:child_process";
// Create a new MCP server instance
const server = new McpServer({
name: "emacs-mcp",
version: "0.0.1",
capabilities: {
tools: {},
},
instructions:
"This server provides access to evaluate Emacs Lisp expressions via emacsclient in the currently visible Emacs buffer. You can evaluate code or capture visible text content from the active Emacs window. Make sure Emacs is running with server mode enabled (M-x server-start). Note that many Emacs Lisp expressions modify state but only return 't' to indicate success. When using emacs_eval to run such commands, follow up with emacs_get_context or emacs_get_visible_text to verify the actual state changes. Example pattern: First run emacs_eval with your command, then run emacs_get_context to check the new state.",
});
/**
* Safely escape an Emacs Lisp expression for passing to emacsclient --eval
* @param {string} expression - The Emacs Lisp expression to escape
* @returns {string} - The escaped expression
*/
function escapeEmacsExpression(expression) {
// Replace double quotes with escaped double quotes
// Replace backslashes with escaped backslashes
return expression.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
/**
* Check if Emacs server is running and accessible
* @returns {boolean} - True if Emacs server is running, false otherwise
*/
function isEmacsServerRunning() {
try {
execSync('emacsclient --eval "t"', { encoding: "utf8" });
return true;
} catch (error) {
return false;
}
}
/**
* Creates a standard error response for when the Emacs server is not running
* @returns {Object} - Error response object conforming to MCP protocol
*/
function createServerNotRunningError() {
return {
content: [
{
type: "text",
text: "Error: Emacs server is not running. Please start it with M-x server-start in Emacs.",
},
],
isError: true,
};
}
// Check if Emacs server is running on startup
if (!isEmacsServerRunning()) {
console.error("Warning: Emacs server does not appear to be running.");
console.error("Please start the Emacs server with M-x server-start");
}
/**
* Tool handler for emacs_eval - Evaluates Emacs Lisp expressions in the current buffer
* @param {Object} params - Parameters from the tool call
* @param {string} params.expression - The Emacs Lisp expression to evaluate
* @returns {Object} - Response object with evaluation result or error
*/
async function evalEmacsExpression({ expression }) {
try {
// Check if Emacs server is running
if (!isEmacsServerRunning()) {
return createServerNotRunningError();
}
// Run emacsclient --eval with the given expression, wrapping it to target the visible buffer
const result = execSync(
`emacsclient --eval "(with-current-buffer (window-buffer (selected-window)) ${escapeEmacsExpression(expression)})"`,
{
encoding: "utf8",
},
).trim();
return {
content: [
{
type: "text",
text: result,
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error evaluating expression: ${error.message}\nCommand may have timed out or failed to execute properly.`,
},
],
isError: true,
};
}
}
// Register the emacs_eval tool
server.tool(
"emacs_eval",
"Evaluate a Lisp expression in the currently visible Emacs buffer and return the result. Many Emacs Lisp expressions mutate state in Emacs and simply return 't' to indicate success rather than returning the changed state. After executing expressions that may change state, use emacs_get_context or emacs_get_visible_text to check the resulting state changes.",
{
expression: z.string().describe("Emacs Lisp expression to evaluate"),
},
evalEmacsExpression,
{
annotations: {
readOnlyHint: false, // This tool can modify Emacs state
destructiveHint: true, // This tool could make destructive changes
idempotentHint: false, // Repeated calls might have different effects
openWorldHint: false, // This tool interacts with the closed world of Emacs
},
},
);
/**
* Tool handler for emacs_get_visible_text - Gets the visible text in the current Emacs window
* @returns {Object} - Response object with visible text content or error
*/
async function getEmacsVisibleText() {
try {
// Check if Emacs server is running
if (!isEmacsServerRunning()) {
return createServerNotRunningError();
}
// This Lisp code gets the visible portion of the buffer in the selected window
const visibleTextExpression = `
(with-current-buffer (window-buffer (selected-window))
(let ((start (window-start))
(end (window-end nil t)))
(if (and start end)
(buffer-substring-no-properties start end)
"No visible text found")))
`;
const result = execSync(
`emacsclient --eval "${escapeEmacsExpression(visibleTextExpression)}"`,
{
encoding: "utf8",
},
).trim();
return {
content: [
{
type: "text",
text: result,
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error getting visible text: ${error.message}\nThe window or buffer may be in an inconsistent state.`,
},
],
isError: true,
};
}
}
// Tool to get visible text content from Emacs
server.tool(
"emacs_get_visible_text",
"Get the text content currently visible in the active Emacs window",
{},
getEmacsVisibleText,
{
annotations: {
readOnlyHint: true, // This tool doesn't modify Emacs state
openWorldHint: false, // This tool interacts with the closed world of Emacs
},
},
);
/**
* Tool handler for emacs_get_context - Gets information about the current Emacs buffer state
* @returns {Object} - Response object with buffer context information or error
*/
async function getEmacsContext() {
try {
// Check if Emacs server is running
if (!isEmacsServerRunning()) {
return createServerNotRunningError();
}
// Lisp code to get detailed context of the visible buffer
const contextExpression = `
(with-current-buffer (window-buffer (selected-window))
(format
"Buffer: %s\nMode: %s\nPoint: %d\nLine Number: %d\nColumn: %d\nFile: %s\nModified: %s\nTotal Lines: %d"
(buffer-name)
major-mode
(point)
(line-number-at-pos)
(current-column)
(or buffer-file-name "Not visiting a file")
(if (buffer-modified-p) "Yes" "No")
(count-lines (point-min) (point-max))))
`;
const result = execSync(
`emacsclient --eval "${escapeEmacsExpression(contextExpression)}"`,
{
encoding: "utf8",
},
).trim();
return {
content: [
{
type: "text",
text: result,
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error getting Emacs context: ${error.message}\nThere may be an issue accessing the current buffer or window information.`,
},
],
isError: true,
};
}
}
// Tool to get context about the current Emacs state
server.tool(
"emacs_get_context",
"Get contextual information about the currently visible Emacs buffer (name, mode, point position, etc)",
{},
getEmacsContext,
{
annotations: {
readOnlyHint: true, // This tool doesn't modify Emacs state
openWorldHint: false, // This tool interacts with the closed world of Emacs
},
},
);
// Start the server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Emacs MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});