imap-mcp 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -0
- package/dist/access.js +117 -0
- package/dist/access.test.js +80 -0
- package/dist/index.js +21 -7
- package/dist/index.test.js +59 -10
- package/dist/tools/create-draft.js +74 -76
- package/dist/tools/create-draft.test.js +49 -32
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -68,10 +68,30 @@ npx tsc
|
|
|
68
68
|
node dist/index.js
|
|
69
69
|
```
|
|
70
70
|
|
|
71
|
+
## Access levels
|
|
72
|
+
|
|
73
|
+
`--access` or `MCP_ACCESS` sets what the agent may do through imap-mcp. The flag wins when both are set; changing the level needs a restart of the server.
|
|
74
|
+
|
|
75
|
+
| Level | The agent may | Tools |
|
|
76
|
+
| --- | --- | --- |
|
|
77
|
+
| `read-only` | Read the mailbox | None yet |
|
|
78
|
+
| `no-send` | Also change the mailbox, but send nothing and reach no one else | `create_draft` |
|
|
79
|
+
| `everything` (default) | Also reach other people | `create_draft` |
|
|
80
|
+
|
|
81
|
+
A tool outside the level is left out of the tool list, and a call to it is refused without changing anything. An unknown value stops the server at start with exit code 2. The level is logged on stderr at start.
|
|
82
|
+
|
|
83
|
+
For example, to start the server read-only:
|
|
84
|
+
|
|
85
|
+
```json
|
|
86
|
+
"args": ["imap-mcp", "--access", "read-only"]
|
|
87
|
+
```
|
|
88
|
+
|
|
71
89
|
## Available Tools
|
|
72
90
|
|
|
73
91
|
### `create_draft`
|
|
74
92
|
|
|
93
|
+
Access level: `no-send`.
|
|
94
|
+
|
|
75
95
|
Creates a draft email message and saves it to the IMAP server's drafts folder.
|
|
76
96
|
|
|
77
97
|
**Parameters:**
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Access levels: what an agent may do through this server, set by the user
|
|
2
|
+
// with --access or MCP_ACCESS (the names, values and default are
|
|
3
|
+
// langmail-mcp's). Each level offers its own tools plus those of the levels
|
|
4
|
+
// below.
|
|
5
|
+
//
|
|
6
|
+
// read-only reads the mailbox.
|
|
7
|
+
// no-send also changes the mailbox, such as saving drafts. Nothing
|
|
8
|
+
// leaves it and nobody else is told.
|
|
9
|
+
// everything also reaches other people, such as sending mail.
|
|
10
|
+
//
|
|
11
|
+
// A tool outside the level is left out of the tool list. A client may still
|
|
12
|
+
// call it from a list it cached at a higher level; that call gets an in-band
|
|
13
|
+
// `isError` result that says why and where the level is changed, rather than
|
|
14
|
+
// the SDK's "Tool X not found", which gives the agent no reason and no next
|
|
15
|
+
// step.
|
|
16
|
+
import { parseArgs } from "node:util";
|
|
17
|
+
import { CallToolRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
18
|
+
export const ACCESS_LEVELS = [
|
|
19
|
+
"read-only",
|
|
20
|
+
"no-send",
|
|
21
|
+
"everything",
|
|
22
|
+
];
|
|
23
|
+
const DEFAULT_ACCESS = "everything";
|
|
24
|
+
// The level of every tool. Registering a tool that has none here fails, so
|
|
25
|
+
// every test that builds the server fails until it gets one.
|
|
26
|
+
export const TOOL_ACCESS = {
|
|
27
|
+
create_draft: "no-send",
|
|
28
|
+
};
|
|
29
|
+
const NAMES = {
|
|
30
|
+
everything: "Everything",
|
|
31
|
+
"no-send": "Change, never send",
|
|
32
|
+
"read-only": "Read only",
|
|
33
|
+
};
|
|
34
|
+
const ALLOWS = {
|
|
35
|
+
everything: "",
|
|
36
|
+
"no-send": ", which lets it change the mailbox, such as saving drafts, but not send mail or reach anyone else",
|
|
37
|
+
"read-only": ", which lets it read the mailbox but not change or send anything",
|
|
38
|
+
};
|
|
39
|
+
const isAccessLevel = (raw) => ACCESS_LEVELS.includes(raw);
|
|
40
|
+
/**
|
|
41
|
+
* Reads the level from `--access`, else `MCP_ACCESS`, else the default. Pure:
|
|
42
|
+
* the caller prints the message and exits.
|
|
43
|
+
*/
|
|
44
|
+
export function parseAccess(argv, env) {
|
|
45
|
+
// Not strict: imap-mcp ignored its arguments before this flag, so a stray
|
|
46
|
+
// one must not stop a setup that started until now.
|
|
47
|
+
const { values } = parseArgs({
|
|
48
|
+
args: argv,
|
|
49
|
+
options: { access: { type: "string" } },
|
|
50
|
+
strict: false,
|
|
51
|
+
allowPositionals: true,
|
|
52
|
+
});
|
|
53
|
+
// A bare `--access` comes back as true: an empty level, not an unset one.
|
|
54
|
+
const flag = values.access === undefined
|
|
55
|
+
? undefined
|
|
56
|
+
: typeof values.access === "string"
|
|
57
|
+
? values.access.trim()
|
|
58
|
+
: "";
|
|
59
|
+
const raw = flag ?? (env.MCP_ACCESS?.trim() || DEFAULT_ACCESS);
|
|
60
|
+
if (isAccessLevel(raw))
|
|
61
|
+
return { ok: true, level: raw };
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
message: `imap-mcp cannot start: MCP_ACCESS (--access): "${raw}" is not an access level; use ${ACCESS_LEVELS.join(", ")}`,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const allows = (level, tool) => ACCESS_LEVELS.indexOf(TOOL_ACCESS[tool]) <= ACCESS_LEVELS.indexOf(level);
|
|
68
|
+
export const refusalText = (tool, level) => `${tool} is not available: the user started this server with ${NAMES[level]} access${ALLOWS[level]}. Nothing was changed or sent. The user can change the access level by restarting the server with the --access option.`;
|
|
69
|
+
/**
|
|
70
|
+
* Offers only the tools `level` allows. Call right after constructing the
|
|
71
|
+
* server, before any tool is registered.
|
|
72
|
+
*/
|
|
73
|
+
export function restrictToAccess(server, level) {
|
|
74
|
+
const excluded = new Set();
|
|
75
|
+
// A tool outside the level is still registered, but disabled, so the SDK
|
|
76
|
+
// leaves it out of tools/list and installs its tools/call handler even when
|
|
77
|
+
// the level allows no tool at all.
|
|
78
|
+
const restrict = (register) => {
|
|
79
|
+
return (name, ...rest) => {
|
|
80
|
+
if (!Object.hasOwn(TOOL_ACCESS, name)) {
|
|
81
|
+
throw new Error(`Tool ${name} has no access level: add it to TOOL_ACCESS in src/access.ts`);
|
|
82
|
+
}
|
|
83
|
+
const registered = register(name, ...rest);
|
|
84
|
+
if (!allows(level, name)) {
|
|
85
|
+
excluded.add(name);
|
|
86
|
+
registered.disable();
|
|
87
|
+
}
|
|
88
|
+
return registered;
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
server.tool = restrict(server.tool.bind(server));
|
|
92
|
+
server.registerTool = restrict(server.registerTool.bind(server));
|
|
93
|
+
// McpServer installs its tools/call handler with the first tool. Wrap it as
|
|
94
|
+
// it is installed, so a call to an excluded tool is answered here.
|
|
95
|
+
const lowLevel = server.server;
|
|
96
|
+
const setRequestHandler = lowLevel.setRequestHandler.bind(lowLevel);
|
|
97
|
+
const patched = (schema, handler) => {
|
|
98
|
+
if (schema !== CallToolRequestSchema) {
|
|
99
|
+
setRequestHandler(schema, handler);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const call = handler;
|
|
103
|
+
setRequestHandler(schema, (request, extra) => {
|
|
104
|
+
const name = request.params?.name;
|
|
105
|
+
if (typeof name === "string" && excluded.has(name)) {
|
|
106
|
+
const result = {
|
|
107
|
+
content: [{ type: "text", text: refusalText(name, level) }],
|
|
108
|
+
isError: true,
|
|
109
|
+
};
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
return call(request, extra);
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
lowLevel.setRequestHandler =
|
|
116
|
+
patched;
|
|
117
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { z } from "zod/v4";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
5
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
6
|
+
import { parseAccess, refusalText, restrictToAccess, TOOL_ACCESS, } from "./access.js";
|
|
7
|
+
describe("parseAccess", () => {
|
|
8
|
+
it("defaults to everything", () => {
|
|
9
|
+
expect(parseAccess([], {})).toEqual({ ok: true, level: "everything" });
|
|
10
|
+
});
|
|
11
|
+
it("reads MCP_ACCESS", () => {
|
|
12
|
+
expect(parseAccess([], { MCP_ACCESS: "no-send" })).toEqual({
|
|
13
|
+
ok: true,
|
|
14
|
+
level: "no-send",
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
it("takes the flag over the variable", () => {
|
|
18
|
+
expect(parseAccess(["--access=read-only"], { MCP_ACCESS: "everything" })).toEqual({ ok: true, level: "read-only" });
|
|
19
|
+
});
|
|
20
|
+
it("rejects --access without a value", () => {
|
|
21
|
+
expect(parseAccess(["--access"], { MCP_ACCESS: "read-only" }).ok).toBe(false);
|
|
22
|
+
});
|
|
23
|
+
it("rejects an unknown value, naming the setting, flag and values", () => {
|
|
24
|
+
const result = parseAccess(["--access", "all"], {});
|
|
25
|
+
expect(result.ok).toBe(false);
|
|
26
|
+
expect(!result.ok && result.message).toBe('imap-mcp cannot start: MCP_ACCESS (--access): "all" is not an access level; use read-only, no-send, everything');
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
async function connect(level) {
|
|
30
|
+
const server = new McpServer({ name: "test", version: "0" });
|
|
31
|
+
restrictToAccess(server, level);
|
|
32
|
+
let calls = 0;
|
|
33
|
+
server.tool("create_draft", "Creates a draft", { to: z.string() }, () => {
|
|
34
|
+
calls++;
|
|
35
|
+
return { content: [{ type: "text", text: "saved" }] };
|
|
36
|
+
});
|
|
37
|
+
const client = new Client({ name: "client", version: "0" });
|
|
38
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
39
|
+
await server.connect(serverTransport);
|
|
40
|
+
await client.connect(clientTransport);
|
|
41
|
+
return { client, calls: () => calls };
|
|
42
|
+
}
|
|
43
|
+
describe("restrictToAccess", () => {
|
|
44
|
+
it("files create_draft under no-send", () => {
|
|
45
|
+
expect(TOOL_ACCESS.create_draft).toBe("no-send");
|
|
46
|
+
});
|
|
47
|
+
it.each(["no-send", "everything"])("offers and runs create_draft at %s", async (level) => {
|
|
48
|
+
const { client, calls } = await connect(level);
|
|
49
|
+
const { tools } = await client.listTools();
|
|
50
|
+
expect(tools.map((t) => t.name)).toEqual(["create_draft"]);
|
|
51
|
+
const result = await client.callTool({
|
|
52
|
+
name: "create_draft",
|
|
53
|
+
arguments: { to: "jane@example.com" },
|
|
54
|
+
});
|
|
55
|
+
expect(result.isError).toBeFalsy();
|
|
56
|
+
expect(calls()).toBe(1);
|
|
57
|
+
});
|
|
58
|
+
it("leaves create_draft out at read-only and refuses a cached call", async () => {
|
|
59
|
+
const { client, calls } = await connect("read-only");
|
|
60
|
+
const { tools } = await client.listTools();
|
|
61
|
+
expect(tools).toEqual([]);
|
|
62
|
+
const result = await client.callTool({
|
|
63
|
+
name: "create_draft",
|
|
64
|
+
arguments: { to: "jane@example.com" },
|
|
65
|
+
});
|
|
66
|
+
expect(result).toEqual({
|
|
67
|
+
content: [
|
|
68
|
+
{ type: "text", text: refusalText("create_draft", "read-only") },
|
|
69
|
+
],
|
|
70
|
+
isError: true,
|
|
71
|
+
});
|
|
72
|
+
expect(refusalText("create_draft", "read-only")).toBe("create_draft is not available: the user started this server with Read only access, which lets it read the mailbox but not change or send anything. Nothing was changed or sent. The user can change the access level by restarting the server with the --access option.");
|
|
73
|
+
expect(calls()).toBe(0);
|
|
74
|
+
});
|
|
75
|
+
it("fails to register a tool without a level", () => {
|
|
76
|
+
const server = new McpServer({ name: "test", version: "0" });
|
|
77
|
+
restrictToAccess(server, "everything");
|
|
78
|
+
expect(() => server.registerTool("send_draft", {}, () => ({ content: [] }))).toThrow("Tool send_draft has no access level");
|
|
79
|
+
});
|
|
80
|
+
});
|
package/dist/index.js
CHANGED
|
@@ -1,27 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "dotenv/config";
|
|
3
|
-
import
|
|
3
|
+
import { ImapFlow } from "imapflow";
|
|
4
4
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
5
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
|
+
import { parseAccess, restrictToAccess } from "./access.js";
|
|
6
7
|
import { registerCreateDraft } from "./tools/create-draft.js";
|
|
7
8
|
const server = new McpServer({
|
|
8
9
|
name: "imap-mcp",
|
|
9
10
|
version: "0.1.0",
|
|
10
11
|
});
|
|
11
12
|
export async function main() {
|
|
13
|
+
const access = parseAccess(process.argv.slice(2), process.env);
|
|
14
|
+
if (!access.ok) {
|
|
15
|
+
console.error(access.message);
|
|
16
|
+
process.exit(2);
|
|
17
|
+
}
|
|
18
|
+
restrictToAccess(server, access.level);
|
|
12
19
|
const imapConfig = {
|
|
13
|
-
user: process.env.IMAP_USERNAME || "",
|
|
14
|
-
password: process.env.IMAP_PASSWORD || "",
|
|
15
20
|
host: process.env.IMAP_HOST || "",
|
|
16
21
|
port: parseInt(process.env.IMAP_PORT || "993"),
|
|
17
|
-
|
|
18
|
-
|
|
22
|
+
secure: process.env.IMAP_USE_SSL === "true",
|
|
23
|
+
auth: {
|
|
24
|
+
user: process.env.IMAP_USERNAME || "",
|
|
25
|
+
pass: process.env.IMAP_PASSWORD || "",
|
|
26
|
+
},
|
|
27
|
+
tls: { rejectUnauthorized: false },
|
|
28
|
+
// Like the imap package, never upgrade a non-SSL connection with STARTTLS.
|
|
29
|
+
doSTARTTLS: false,
|
|
30
|
+
// imapflow logs to stdout by default, which carries the MCP protocol.
|
|
31
|
+
logger: false,
|
|
19
32
|
};
|
|
20
|
-
|
|
21
|
-
registerCreateDraft(client, server);
|
|
33
|
+
registerCreateDraft(() => new ImapFlow(imapConfig), server);
|
|
22
34
|
// Start receiving messages on stdin and sending messages on stdout
|
|
23
35
|
const transport = new StdioServerTransport();
|
|
24
36
|
await server.connect(transport);
|
|
37
|
+
// stdout is the MCP transport, so the log goes to stderr.
|
|
38
|
+
console.error(`imap-mcp started with access level ${access.level}`);
|
|
25
39
|
}
|
|
26
40
|
// Only run main if this file is executed directly (not imported)
|
|
27
41
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
package/dist/index.test.js
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
3
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
-
import
|
|
4
|
+
import { ImapFlow } from "imapflow";
|
|
5
|
+
import { restrictToAccess } from "./access.js";
|
|
5
6
|
// Mock the dependencies
|
|
6
7
|
vi.mock("@modelcontextprotocol/sdk/server/mcp.js");
|
|
7
8
|
vi.mock("@modelcontextprotocol/sdk/server/stdio.js");
|
|
8
|
-
vi.mock("
|
|
9
|
+
vi.mock("imapflow");
|
|
9
10
|
vi.mock("./tools/create-draft.js", () => ({
|
|
10
11
|
registerCreateDraft: vi.fn(),
|
|
11
12
|
}));
|
|
13
|
+
vi.mock("./access.js", async (importOriginal) => ({
|
|
14
|
+
...(await importOriginal()),
|
|
15
|
+
restrictToAccess: vi.fn(),
|
|
16
|
+
}));
|
|
17
|
+
import { registerCreateDraft } from "./tools/create-draft.js";
|
|
12
18
|
describe("main", () => {
|
|
19
|
+
const argv = process.argv;
|
|
13
20
|
beforeEach(() => {
|
|
14
21
|
vi.clearAllMocks();
|
|
22
|
+
process.argv = ["node", "imap-mcp"];
|
|
23
|
+
delete process.env.MCP_ACCESS;
|
|
15
24
|
// Mock environment variables
|
|
16
25
|
process.env.IMAP_USERNAME = "test@example.com";
|
|
17
26
|
process.env.IMAP_PASSWORD = "testpass";
|
|
@@ -20,17 +29,23 @@ describe("main", () => {
|
|
|
20
29
|
process.env.IMAP_USE_SSL = "true";
|
|
21
30
|
});
|
|
22
31
|
afterEach(() => {
|
|
32
|
+
process.argv = argv;
|
|
33
|
+
delete process.env.MCP_ACCESS;
|
|
23
34
|
vi.restoreAllMocks();
|
|
24
35
|
});
|
|
36
|
+
function mockServer() {
|
|
37
|
+
const server = { connect: vi.fn().mockResolvedValue(undefined) };
|
|
38
|
+
vi.mocked(McpServer).mockImplementation(() => server);
|
|
39
|
+
vi.mocked(StdioServerTransport).mockImplementation(() => ({}));
|
|
40
|
+
return server;
|
|
41
|
+
}
|
|
25
42
|
it("starts the mcp server", async () => {
|
|
26
43
|
const mockServer = {
|
|
27
44
|
connect: vi.fn().mockResolvedValue(undefined),
|
|
28
45
|
};
|
|
29
46
|
const mockTransport = {};
|
|
30
|
-
const mockImap = {};
|
|
31
47
|
vi.mocked(McpServer).mockImplementation(() => mockServer);
|
|
32
48
|
vi.mocked(StdioServerTransport).mockImplementation(() => mockTransport);
|
|
33
|
-
vi.mocked(Imap).mockImplementation(() => mockImap);
|
|
34
49
|
// Import and run main function
|
|
35
50
|
const { main } = await import("./index.js");
|
|
36
51
|
await main();
|
|
@@ -39,17 +54,51 @@ describe("main", () => {
|
|
|
39
54
|
name: "imap-mcp",
|
|
40
55
|
version: "0.1.0",
|
|
41
56
|
});
|
|
42
|
-
// Verify IMAP client
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
57
|
+
// Verify each tool call gets an IMAP client built from the environment
|
|
58
|
+
const createClient = vi.mocked(registerCreateDraft).mock.calls[0][0];
|
|
59
|
+
createClient();
|
|
60
|
+
expect(ImapFlow).toHaveBeenCalledWith({
|
|
46
61
|
host: "imap.example.com",
|
|
47
62
|
port: 993,
|
|
48
|
-
|
|
49
|
-
|
|
63
|
+
secure: true,
|
|
64
|
+
auth: { user: "test@example.com", pass: "testpass" },
|
|
65
|
+
tls: { rejectUnauthorized: false },
|
|
66
|
+
doSTARTTLS: false,
|
|
67
|
+
logger: false,
|
|
50
68
|
});
|
|
51
69
|
// Verify transport was created and server connected
|
|
52
70
|
expect(StdioServerTransport).toHaveBeenCalled();
|
|
53
71
|
expect(mockServer.connect).toHaveBeenCalledWith(mockTransport);
|
|
54
72
|
});
|
|
73
|
+
it("defaults to everything and logs the level on stderr", async () => {
|
|
74
|
+
mockServer();
|
|
75
|
+
const stderr = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
76
|
+
const { main } = await import("./index.js");
|
|
77
|
+
await main();
|
|
78
|
+
expect(restrictToAccess).toHaveBeenCalledWith(expect.anything(), "everything");
|
|
79
|
+
expect(stderr).toHaveBeenCalledWith("imap-mcp started with access level everything");
|
|
80
|
+
});
|
|
81
|
+
it("takes the --access flag over MCP_ACCESS", async () => {
|
|
82
|
+
mockServer();
|
|
83
|
+
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
84
|
+
process.env.MCP_ACCESS = "no-send";
|
|
85
|
+
process.argv = ["node", "imap-mcp", "--access", "read-only"];
|
|
86
|
+
const { main } = await import("./index.js");
|
|
87
|
+
await main();
|
|
88
|
+
expect(restrictToAccess).toHaveBeenCalledWith(expect.anything(), "read-only");
|
|
89
|
+
});
|
|
90
|
+
it("stops with exit code 2 on an unknown level", async () => {
|
|
91
|
+
const server = mockServer();
|
|
92
|
+
const stderr = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
93
|
+
const exit = vi.spyOn(process, "exit").mockImplementation(() => {
|
|
94
|
+
throw new Error("exit");
|
|
95
|
+
});
|
|
96
|
+
process.env.MCP_ACCESS = "send-only";
|
|
97
|
+
const { main } = await import("./index.js");
|
|
98
|
+
await expect(main()).rejects.toThrow("exit");
|
|
99
|
+
expect(exit).toHaveBeenCalledWith(2);
|
|
100
|
+
expect(stderr).toHaveBeenCalledTimes(1);
|
|
101
|
+
expect(stderr).toHaveBeenCalledWith('imap-mcp cannot start: MCP_ACCESS (--access): "send-only" is not an access level; use read-only, no-send, everything');
|
|
102
|
+
expect(server.connect).not.toHaveBeenCalled();
|
|
103
|
+
});
|
|
55
104
|
});
|
|
@@ -1,91 +1,89 @@
|
|
|
1
1
|
import { z } from "zod/v4";
|
|
2
|
-
|
|
2
|
+
/** Folders tried in order when the server marks none as `\Drafts`. */
|
|
3
|
+
const FALLBACK_DRAFTS_FOLDERS = ["INBOX.Drafts", "Drafts"];
|
|
4
|
+
export function registerCreateDraft(createClient, server) {
|
|
3
5
|
server.tool("create_draft", "Creates a draft email message", {
|
|
4
6
|
to: z.string(),
|
|
5
7
|
subject: z.string(),
|
|
6
8
|
body: z.string(),
|
|
7
9
|
from: z.string().optional(),
|
|
8
10
|
}, async ({ to, subject, body, from }) => {
|
|
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
|
-
body,
|
|
48
|
-
].join("\r\n");
|
|
49
|
-
client.append(message, { flags: ["\\Draft"] }, (err) => {
|
|
50
|
-
if (err) {
|
|
51
|
-
reject(new Error(`Failed to create draft: ${err.message}`));
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
resolve({
|
|
55
|
-
content: [
|
|
56
|
-
{
|
|
57
|
-
type: "text",
|
|
58
|
-
text: `Draft created successfully for ${to}`,
|
|
59
|
-
},
|
|
60
|
-
],
|
|
61
|
-
});
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
client.once("error", (err) => {
|
|
66
|
-
reject(new Error(`IMAP connection error: ${err.message}`));
|
|
67
|
-
});
|
|
68
|
-
client.connect();
|
|
69
|
-
});
|
|
11
|
+
const client = createClient();
|
|
12
|
+
// An unhandled "error" event would crash the server; the failing
|
|
13
|
+
// command rejects as well, so the tool call reports it.
|
|
14
|
+
client.on("error", () => { });
|
|
15
|
+
try {
|
|
16
|
+
await client.connect();
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
client.close();
|
|
20
|
+
throw new Error(`IMAP connection error: ${errorMessage(err)}`);
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const draftsPath = await openDraftsFolder(client);
|
|
24
|
+
const message = [
|
|
25
|
+
`From: ${from || process.env.IMAP_USERNAME || ""}`,
|
|
26
|
+
`To: ${to}`,
|
|
27
|
+
`Subject: ${subject}`,
|
|
28
|
+
"",
|
|
29
|
+
body,
|
|
30
|
+
].join("\r\n");
|
|
31
|
+
try {
|
|
32
|
+
await client.append(draftsPath, message, ["\\Draft"]);
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
throw new Error(`Failed to create draft: ${errorMessage(err)}`);
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
content: [
|
|
39
|
+
{
|
|
40
|
+
type: "text",
|
|
41
|
+
text: `Draft created successfully for ${to}`,
|
|
42
|
+
},
|
|
43
|
+
],
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await client.logout().catch(() => client.close());
|
|
48
|
+
}
|
|
70
49
|
});
|
|
71
50
|
}
|
|
72
51
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
52
|
+
* Opens the folder marked `\Drafts`, or else the first fallback folder that
|
|
53
|
+
* exists, and returns its path.
|
|
75
54
|
*/
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
55
|
+
async function openDraftsFolder(client) {
|
|
56
|
+
const folders = await client.list().catch(() => []);
|
|
57
|
+
const marked = findDraftsFolder(folders);
|
|
58
|
+
const candidates = marked ? [marked] : FALLBACK_DRAFTS_FOLDERS;
|
|
59
|
+
let lastError;
|
|
60
|
+
for (const path of candidates) {
|
|
61
|
+
try {
|
|
62
|
+
await client.mailboxOpen(path);
|
|
63
|
+
return path;
|
|
83
64
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (found)
|
|
87
|
-
return found;
|
|
65
|
+
catch (err) {
|
|
66
|
+
lastError = err;
|
|
88
67
|
}
|
|
89
68
|
}
|
|
90
|
-
|
|
69
|
+
throw new Error(`Failed to open drafts folder: ${errorMessage(lastError)}`);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Returns the path of the folder the server marks with the `\Drafts`
|
|
73
|
+
* special-use attribute (RFC 6154), or undefined if none is marked.
|
|
74
|
+
*/
|
|
75
|
+
export function findDraftsFolder(folders) {
|
|
76
|
+
return folders.find((folder) => [...folder.flags].some((flag) => flag.toLowerCase() === "\\drafts"))?.path;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* imapflow reports a server's NO or BAD as "Command failed" and keeps the
|
|
80
|
+
* server's reason in `responseText`, which is what the user needs to see.
|
|
81
|
+
*/
|
|
82
|
+
function errorMessage(err) {
|
|
83
|
+
if (!(err instanceof Error))
|
|
84
|
+
return String(err);
|
|
85
|
+
const { responseText } = err;
|
|
86
|
+
return typeof responseText === "string" && responseText
|
|
87
|
+
? responseText
|
|
88
|
+
: err.message;
|
|
91
89
|
}
|
|
@@ -1,32 +1,38 @@
|
|
|
1
1
|
import { describe, expect, test, vi } from "vitest";
|
|
2
2
|
import { registerCreateDraft } from "./create-draft.js";
|
|
3
|
-
function
|
|
3
|
+
function folder(path, flags) {
|
|
4
|
+
const segments = path.split("/");
|
|
4
5
|
return {
|
|
5
|
-
|
|
6
|
+
path,
|
|
7
|
+
pathAsListed: path,
|
|
8
|
+
name: segments[segments.length - 1],
|
|
6
9
|
delimiter: "/",
|
|
7
|
-
|
|
8
|
-
|
|
10
|
+
parent: segments.slice(0, -1),
|
|
11
|
+
parentPath: segments.slice(0, -1).join("/"),
|
|
12
|
+
flags: new Set(flags),
|
|
13
|
+
listed: true,
|
|
14
|
+
subscribed: true,
|
|
9
15
|
};
|
|
10
16
|
}
|
|
11
|
-
function setup(
|
|
12
|
-
const listeners = {};
|
|
17
|
+
function setup(folders, existing, { connectError } = {}) {
|
|
13
18
|
let openedBox;
|
|
14
19
|
const client = {
|
|
15
|
-
|
|
16
|
-
|
|
20
|
+
on: vi.fn(),
|
|
21
|
+
connect: vi.fn(async () => {
|
|
22
|
+
if (connectError)
|
|
23
|
+
throw connectError;
|
|
17
24
|
}),
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
openedBox = name;
|
|
23
|
-
cb(null);
|
|
24
|
-
}
|
|
25
|
-
else {
|
|
26
|
-
cb(new Error(`Mailbox doesn't exist: ${name}`));
|
|
25
|
+
list: vi.fn(async () => folders),
|
|
26
|
+
mailboxOpen: vi.fn(async (path) => {
|
|
27
|
+
if (!existing.includes(path)) {
|
|
28
|
+
throw new Error(`Mailbox doesn't exist: ${path}`);
|
|
27
29
|
}
|
|
30
|
+
openedBox = path;
|
|
31
|
+
return { path };
|
|
28
32
|
}),
|
|
29
|
-
append: vi.fn((
|
|
33
|
+
append: vi.fn(async () => ({ destination: openedBox })),
|
|
34
|
+
logout: vi.fn(async () => { }),
|
|
35
|
+
close: vi.fn(),
|
|
30
36
|
};
|
|
31
37
|
let handler;
|
|
32
38
|
const server = {
|
|
@@ -34,33 +40,33 @@ function setup(boxes, existing) {
|
|
|
34
40
|
handler = args[args.length - 1];
|
|
35
41
|
}),
|
|
36
42
|
};
|
|
37
|
-
registerCreateDraft(client, server);
|
|
43
|
+
registerCreateDraft(() => client, server);
|
|
38
44
|
const run = () => handler({ to: "jane@example.com", subject: "Hi", body: "Hello" });
|
|
39
45
|
return { client, server, run, openedBox: () => openedBox };
|
|
40
46
|
}
|
|
41
47
|
describe("create_draft", () => {
|
|
42
48
|
test("registers the tool as create_draft", () => {
|
|
43
|
-
const { server } = setup(
|
|
49
|
+
const { server } = setup([folder("Drafts", ["\\Drafts"])], ["Drafts"]);
|
|
44
50
|
expect(server.tool).toHaveBeenCalledWith("create_draft", expect.any(String), expect.any(Object), expect.any(Function));
|
|
45
51
|
});
|
|
46
52
|
test("saves to the folder marked \\Drafts, whatever its name and nesting", async () => {
|
|
47
|
-
const { client, run, openedBox } = setup(
|
|
48
|
-
INBOX
|
|
49
|
-
"[Gmail]"
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}, ["[Gmail]/Entwürfe", "Drafts"]);
|
|
53
|
+
const { client, run, openedBox } = setup([
|
|
54
|
+
folder("INBOX", ["\\HasNoChildren"]),
|
|
55
|
+
folder("[Gmail]", ["\\Noselect", "\\HasChildren"]),
|
|
56
|
+
folder("[Gmail]/All Mail", ["\\All"]),
|
|
57
|
+
folder("[Gmail]/Entwürfe", ["\\HasNoChildren", "\\Drafts"]),
|
|
58
|
+
folder("Drafts", []),
|
|
59
|
+
], ["[Gmail]/Entwürfe", "Drafts"]);
|
|
55
60
|
const result = await run();
|
|
56
61
|
expect(openedBox()).toBe("[Gmail]/Entwürfe");
|
|
57
|
-
expect(client.append).
|
|
62
|
+
expect(client.append).toHaveBeenCalledExactlyOnceWith("[Gmail]/Entwürfe", "From: \r\nTo: jane@example.com\r\nSubject: Hi\r\n\r\nHello", ["\\Draft"]);
|
|
58
63
|
expect(result.content[0].text).toBe("Draft created successfully for jane@example.com");
|
|
64
|
+
expect(client.logout).toHaveBeenCalledOnce();
|
|
59
65
|
});
|
|
60
66
|
test("falls back to INBOX.Drafts or Drafts when no folder is marked \\Drafts", async () => {
|
|
61
|
-
const { client, run, openedBox } = setup(
|
|
67
|
+
const { client, run, openedBox } = setup([folder("INBOX", []), folder("Drafts", [])], ["Drafts"]);
|
|
62
68
|
await run();
|
|
63
|
-
expect(client.
|
|
69
|
+
expect(client.mailboxOpen.mock.calls.map((c) => c[0])).toEqual([
|
|
64
70
|
"INBOX.Drafts",
|
|
65
71
|
"Drafts",
|
|
66
72
|
]);
|
|
@@ -68,8 +74,19 @@ describe("create_draft", () => {
|
|
|
68
74
|
expect(client.append).toHaveBeenCalledOnce();
|
|
69
75
|
});
|
|
70
76
|
test("fails when no drafts folder can be opened", async () => {
|
|
71
|
-
const { client, run } = setup(
|
|
77
|
+
const { client, run } = setup([folder("INBOX", [])], []);
|
|
72
78
|
await expect(run()).rejects.toThrow("Failed to open drafts folder");
|
|
73
79
|
expect(client.append).not.toHaveBeenCalled();
|
|
80
|
+
expect(client.logout).toHaveBeenCalledOnce();
|
|
81
|
+
});
|
|
82
|
+
test("reports a connection or login failure as a tool error", async () => {
|
|
83
|
+
// imapflow's shape for a server's NO: a generic message, the reason apart
|
|
84
|
+
const connectError = Object.assign(new Error("Command failed"), {
|
|
85
|
+
responseText: "[AUTHENTICATIONFAILED] Invalid credentials",
|
|
86
|
+
});
|
|
87
|
+
const { client, run } = setup([], [], { connectError });
|
|
88
|
+
await expect(run()).rejects.toThrow("IMAP connection error: [AUTHENTICATIONFAILED] Invalid credentials");
|
|
89
|
+
expect(client.on).toHaveBeenCalledWith("error", expect.any(Function));
|
|
90
|
+
expect(client.list).not.toHaveBeenCalled();
|
|
74
91
|
});
|
|
75
92
|
});
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "imap-mcp",
|
|
3
3
|
"mcpName": "io.github.langmail/imap-mcp",
|
|
4
4
|
"description": "An MCP server that lets your AI agent save email drafts to any IMAP mailbox.",
|
|
5
|
-
"version": "1.0
|
|
5
|
+
"version": "1.1.0",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"bin": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
40
40
|
"dotenv": "^16.5.0",
|
|
41
|
-
"
|
|
41
|
+
"imapflow": "^2.12.2",
|
|
42
42
|
"zod": "^3.25.67"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
@@ -47,7 +47,6 @@
|
|
|
47
47
|
"@semantic-release/git": "^10.0.1",
|
|
48
48
|
"@semantic-release/github": "^12.0.11",
|
|
49
49
|
"@semantic-release/npm": "^13.2.0",
|
|
50
|
-
"@types/imap": "^0.8.42",
|
|
51
50
|
"@types/node": "^24.0.4",
|
|
52
51
|
"eslint": "^9.29.0",
|
|
53
52
|
"eslint-config-prettier": "^10.1.5",
|