@deredex/mcp 0.0.0-stage → 0.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Deredex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # @deredex/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP (Model Context Protocol) server for the platform's REST API. Exposes it as typed tools for Claude Code and other MCP-compatible clients so you can manage tasks, projects, and (in later versions) CRM data by talking to Claude.
4
+
5
+ Authenticates with the same `shdt_` bearer tokens minted at `/admin/api-tokens` on your deployment. Tenant-scoped — a token can only see rows in the tenant it was minted in.
6
+
7
+ **Status: v0.x, unstable.** Breaking changes are expected as the tool surface grows. Not published to public npm yet.
8
+
9
+ ---
10
+
11
+ ## Install
12
+
13
+ Not on public npm yet — install directly from the tarball your operator hands you:
14
+
15
+ ```bash
16
+ npm install -g /path/to/deredex-mcp-<version>.tgz
17
+ ```
18
+
19
+ If the previous release is already installed globally, uninstall it first or this stops with `EEXIST`: see [Upgrading from the previous release](#upgrading-from-the-previous-release).
20
+
21
+ Or in a project:
22
+
23
+ ```bash
24
+ npm install /path/to/deredex-mcp-<version>.tgz
25
+ ```
26
+
27
+ Once published, the standard `npx` install path will work:
28
+
29
+ ```bash
30
+ npx -y @deredex/mcp
31
+ ```
32
+
33
+ ## Configure
34
+
35
+ Mint an API token from `/admin/api-tokens` on your deployment (see the getting-started doc at `/admin/api-tokens/docs`).
36
+
37
+ Add the server to your MCP client's config. For Claude Code, edit `~/.claude.json` (or wherever your `mcpServers` block lives):
38
+
39
+ ```json
40
+ {
41
+ "mcpServers": {
42
+ "deredex": {
43
+ "command": "npx",
44
+ "args": ["-y", "@deredex/mcp"],
45
+ "env": {
46
+ "MCP_BASE_URL": "https://your-host.example.com",
47
+ "MCP_TOKEN": "shdt_..."
48
+ }
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ Restart your MCP client to pick up the new server. Try `whoami` first to confirm auth is wired.
55
+
56
+ ### Environment variables
57
+
58
+ | Variable | Required | Default | Purpose |
59
+ |---|---|---|---|
60
+ | `MCP_BASE_URL` | yes | — | Your deployment origin, e.g. `https://your-host.example.com`. Trailing slashes tolerated. |
61
+ | `MCP_TOKEN` | yes | — | An `shdt_...` bearer token minted at `/admin/api-tokens`. Guard as a secret. |
62
+ | `MCP_REQUEST_TIMEOUT_MS` | no | `30000` | Per-request timeout in milliseconds. A wedged backend surfaces as a `transport error` in the tool result. |
63
+
64
+ A blank value counts as unset.
65
+
66
+ ### Upgrading from the previous release
67
+
68
+ An `mcpServers` block written for the previous release keeps working for this release only. For each variable above that is not set, the server still reads the name the previous release used, and prints a notice to stderr naming the variable to set instead. The command the previous release installed also keeps working for this release only. Move to the names and the command above.
69
+
70
+ If the previous release is installed globally, uninstall it before you install this one. This release installs the command the previous release installed, and npm will not overwrite a command that another package owns, so `npm install -g` over the top stops with `EEXIST` ("File exists"). `npm ls -g --depth=0` lists the global packages, which shows the previous release's name; `npm uninstall -g <that name>` removes it, and then the install command above works. A project install and `npx` are not affected.
71
+
72
+ ## Tools
73
+
74
+ | Tool | Purpose |
75
+ |---|---|
76
+ | `whoami` | Return the identity of the token holder + tenant. Sanity check. |
77
+ | **Projects & tasks** | |
78
+ | `list_projects` | List projects in the tenant. Optionally include archived. |
79
+ | `get_project` | Fetch a single project by UUID. |
80
+ | `create_project` | Create a new project. |
81
+ | `list_tasks` | List tasks, optionally filtered by project / status / assignee. |
82
+ | `get_task` | Fetch a single task by UUID. |
83
+ | `create_task` | Create a task inside a project. |
84
+ | `update_task` | Partial-update a task's fields. |
85
+ | `kanban_move_task` | Move a task on the kanban board (change column + optional position). |
86
+ | `archive_task` | Soft-archive a task. Reversible via `update_task`. |
87
+ | **CRM contacts** | |
88
+ | `list_contacts` | List contacts. Filter by search text, account, owner. |
89
+ | `get_contact` | Fetch a single contact by UUID. |
90
+ | `create_contact` | Create a new contact. First + last name required. |
91
+ | `update_contact` | Partial-update a contact. |
92
+ | `archive_contact` | Soft-archive a contact. |
93
+ | `list_contact_notes` | List timeline notes attached to a contact. |
94
+ | `add_contact_note` | Add a timeline note to a contact. |
95
+ | **CRM accounts** | |
96
+ | `list_accounts` | List accounts. Filter by search text, owner, industry. |
97
+ | `get_account` | Fetch a single account by UUID. |
98
+ | `create_account` | Create a new account. |
99
+ | `update_account` | Partial-update an account. |
100
+ | `archive_account` | Soft-archive an account. |
101
+ | **CRM deals** | |
102
+ | `list_deals` | List deals. Filter by stage, account, owner. |
103
+ | `get_deal` | Fetch a single deal by UUID. |
104
+ | `create_deal` | Create a new deal. |
105
+ | `update_deal` | Partial-update a deal (arbitrary fields). |
106
+ | `move_deal_to_stage` | Change a deal's stage (dedicated tool for the most common transition). |
107
+ | `archive_deal` | Soft-archive a deal. |
108
+ | `list_deal_notes` | List timeline notes attached to a deal. |
109
+ | `add_deal_note` | Add a timeline note to a deal. |
110
+
111
+ More module coverage (social posts, marketing campaigns, webhook/alert stream) lands in later versions.
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ # From services/mcp
117
+ npm install
118
+ npm test # node --test with tsx loader
119
+ npm run build # tsc → dist/
120
+ npm run dev # tsx watch mode against ./src
121
+ ```
122
+
123
+ The HTTP client is fully covered by tests that spin up a `node:http` fake server. No mocking, real fetch.
124
+
125
+ ## License
126
+
127
+ Proprietary. Do not redistribute.
package/dist/client.js ADDED
@@ -0,0 +1,127 @@
1
+ // HTTP client wrapper. Wraps the platform's REST API in a
2
+ // consistent auth + error-mapping shell so every tool handler can
3
+ // call `client.get`/`.post`/`.patch`/`.del` without repeating the
4
+ // Bearer header or the JSON dance.
5
+ import { ShdEspApiError, ShdEspTransportError } from "./errors.js";
6
+ // What a transport error says when a request header was refused before
7
+ // anything was sent. FIXED text: see where rawRequest builds the headers.
8
+ const HEADER_REFUSED = "the request was not sent: a header value is not valid (does MCP_TOKEN hold a line break or another control character?)";
9
+ // createClient returns a bound HttpClient. Uses the global fetch
10
+ // available in Node >= 18. The abort controller enforces
11
+ // requestTimeoutMs; a wedged backend returns as ShdEspTransportError
12
+ // instead of hanging Claude's tool call indefinitely.
13
+ export function createClient(cfg) {
14
+ async function rawRequest(method, path, body, opts) {
15
+ const url = joinURL(cfg.baseURL, path);
16
+ const timeoutMs = opts?.timeoutMs ?? cfg.requestTimeoutMs;
17
+ // The headers are checked HERE, apart from fetch, on purpose. When
18
+ // the HTTP stack refuses a header value, its TypeError QUOTES the
19
+ // value, and the Authorization value is "Bearer <token>". A transport
20
+ // error's text becomes a tool result: the model's context and the
21
+ // session transcript. So a refused header is reported by a fixed
22
+ // sentence, and the TypeError is dropped, cause included, so that
23
+ // nothing that inspects this error can find the value either.
24
+ let headers;
25
+ try {
26
+ headers = new Headers(buildHeaders(cfg, body !== undefined));
27
+ }
28
+ catch {
29
+ throw new ShdEspTransportError(path, HEADER_REFUSED);
30
+ }
31
+ const controller = new AbortController();
32
+ const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
33
+ try {
34
+ const res = await fetch(url, {
35
+ method,
36
+ headers,
37
+ body: body === undefined ? undefined : JSON.stringify(body),
38
+ signal: controller.signal,
39
+ });
40
+ const text = await res.text();
41
+ return { status: res.status, text };
42
+ }
43
+ catch (err) {
44
+ if (err instanceof Error && err.name === "AbortError") {
45
+ throw new ShdEspTransportError(path, `timed out after ${timeoutMs}ms`);
46
+ }
47
+ const message = err instanceof Error ? err.message : String(err);
48
+ throw new ShdEspTransportError(path, message, err);
49
+ }
50
+ finally {
51
+ clearTimeout(timeoutHandle);
52
+ }
53
+ }
54
+ async function request(method, path, body, opts) {
55
+ const { status, text } = await rawRequest(method, path, body, opts);
56
+ if (status < 200 || status >= 300) {
57
+ const message = extractErrorMessage(text, `HTTP ${status}`);
58
+ throw new ShdEspApiError(status, path, message, text);
59
+ }
60
+ // No-body responses (e.g. DELETE) return empty string; return
61
+ // undefined-typed T so callers can use `void` return types.
62
+ if (text.length === 0)
63
+ return undefined;
64
+ try {
65
+ return JSON.parse(text);
66
+ }
67
+ catch {
68
+ throw new ShdEspApiError(status, path, "response was not valid JSON", text);
69
+ }
70
+ }
71
+ return {
72
+ get: (path, opts) => request("GET", path, undefined, opts),
73
+ post: (path, body, opts) => request("POST", path, body, opts),
74
+ patch: (path, body, opts) => request("PATCH", path, body, opts),
75
+ del: (path, opts) => request("DELETE", path, undefined, opts),
76
+ rawGetStatus: async (path, opts) => {
77
+ const { status, text } = await rawRequest("GET", path, undefined, opts);
78
+ if (status < 200 || status >= 300) {
79
+ const message = extractErrorMessage(text, `HTTP ${status}`);
80
+ throw new ShdEspApiError(status, path, message, text);
81
+ }
82
+ if (text.length === 0)
83
+ return { status, body: undefined };
84
+ try {
85
+ return { status, body: JSON.parse(text) };
86
+ }
87
+ catch {
88
+ throw new ShdEspApiError(status, path, "response was not valid JSON", text);
89
+ }
90
+ },
91
+ };
92
+ }
93
+ function buildHeaders(cfg, hasBody) {
94
+ const headers = {
95
+ Authorization: `Bearer ${cfg.token}`,
96
+ Accept: "application/json",
97
+ // Keep the version in step with package.json and index.ts's server
98
+ // version; tests/brand-surface-7687.test.ts fails on drift.
99
+ "User-Agent": "deredex-mcp/0.4.0",
100
+ };
101
+ if (hasBody)
102
+ headers["Content-Type"] = "application/json";
103
+ return headers;
104
+ }
105
+ // joinURL concatenates a base URL + a path, tolerant of trailing
106
+ // slashes on the base and leading slashes on the path.
107
+ function joinURL(base, path) {
108
+ const b = base.replace(/\/+$/, "");
109
+ const p = path.startsWith("/") ? path : `/${path}`;
110
+ return `${b}${p}`;
111
+ }
112
+ // extractErrorMessage tries to pull the backend's `error` field out
113
+ // of a JSON error body. Falls back to the HTTP status text when the
114
+ // body isn't parseable or lacks the field. Never throws.
115
+ function extractErrorMessage(body, fallback) {
116
+ if (!body)
117
+ return fallback;
118
+ try {
119
+ const parsed = JSON.parse(body);
120
+ if (parsed && typeof parsed.error === "string")
121
+ return parsed.error;
122
+ }
123
+ catch {
124
+ // fall through
125
+ }
126
+ return fallback;
127
+ }
package/dist/config.js ADDED
@@ -0,0 +1,88 @@
1
+ // Runtime configuration for the MCP server.
2
+ //
3
+ // Read from env vars — MCP client config files set these when
4
+ // spawning the server, e.g. in Claude Code's mcpServers block:
5
+ //
6
+ // {
7
+ // "deredex": {
8
+ // "command": "npx",
9
+ // "args": ["-y", "@deredex/mcp"],
10
+ // "env": {
11
+ // "MCP_BASE_URL": "https://your-host.example.com",
12
+ // "MCP_TOKEN": "shdt_..."
13
+ // }
14
+ // }
15
+ // }
16
+ //
17
+ // loadConfig never hard-fails on a missing / blank var. main() calls
18
+ // assertConfigured once at startup, so the operator sees a clear
19
+ // message when the server refuses to start, not an obscure 401 on the
20
+ // first tool call.
21
+ // Each setting has a current name and the name the previous release
22
+ // read. The previous names keep working for ONE more release, so an
23
+ // existing mcpServers block does not break on upgrade, and the current
24
+ // name always wins. The choice is made per variable, and a blank value
25
+ // counts as unset (it is trimmed first): a placeholder left blank
26
+ // under the current name never hides a working value under the
27
+ // previous one.
28
+ //
29
+ // This table is the only place the previous names are spelled. Keep it
30
+ // that way (one per line), and keep them out of comments, so the list
31
+ // of remaining hits in tests/brand-surface-7687.test.ts stays exact.
32
+ const ENV_NAMES = {
33
+ baseURL: ["MCP_BASE_URL", "SHD_ESP_BASE_URL"],
34
+ token: ["MCP_TOKEN", "SHD_ESP_TOKEN"],
35
+ requestTimeoutMs: ["MCP_REQUEST_TIMEOUT_MS", "SHD_ESP_REQUEST_TIMEOUT_MS"],
36
+ };
37
+ function lookup(env, [current, previous]) {
38
+ const now = (env[current] ?? "").trim();
39
+ if (now)
40
+ return { value: now, fromPrevious: false };
41
+ const before = (env[previous] ?? "").trim();
42
+ return { value: before, fromPrevious: before !== "" };
43
+ }
44
+ export function loadConfig(env = process.env) {
45
+ const rawBase = lookup(env, ENV_NAMES.baseURL).value;
46
+ const rawToken = lookup(env, ENV_NAMES.token).value;
47
+ const rawTimeout = lookup(env, ENV_NAMES.requestTimeoutMs).value;
48
+ const baseURL = rawBase.replace(/\/+$/, ""); // trim trailing slashes
49
+ const token = rawToken;
50
+ const requestTimeoutMs = rawTimeout ? Number(rawTimeout) : 30_000;
51
+ return { baseURL, token, requestTimeoutMs };
52
+ }
53
+ // legacyEnvNotice returns a one-line notice when a setting was read
54
+ // from its previous name, and null when every setting came from its
55
+ // current name (or is unset). It names only the CURRENT variables: the
56
+ // previous names are honored, not advertised, and this text lands in
57
+ // the MCP client's server log. main() writes it to stderr, never to
58
+ // stdout, which carries the JSON-RPC traffic.
59
+ export function legacyEnvNotice(env = process.env) {
60
+ const stale = Object.values(ENV_NAMES)
61
+ .filter((names) => lookup(env, names).fromPrevious)
62
+ .map(([current]) => current);
63
+ if (stale.length === 0)
64
+ return null;
65
+ return `the previous variable names still work for this release only; set ${stale.join(", ")} instead.`;
66
+ }
67
+ // assertConfigured throws a descriptive error when either required
68
+ // setting is missing, or when the token holds a line break. main() calls
69
+ // it once at startup, so the operator sees "MCP_TOKEN is not set" in the
70
+ // MCP client's server log instead of a network-level 401 on the first
71
+ // tool call.
72
+ //
73
+ // A line break INSIDE the token (trim() only strips the ends) is a paste
74
+ // over two lines. It is refused here, with a sentence that names the
75
+ // variable and never quotes its value: the value is a credential, and
76
+ // this text lands in the MCP client's server log. Without this, every
77
+ // request would be refused by the HTTP stack instead (see client.ts).
78
+ export function assertConfigured(cfg) {
79
+ if (!cfg.baseURL) {
80
+ throw new Error("MCP_BASE_URL is not set. Add it to the mcpServers env block for @deredex/mcp.");
81
+ }
82
+ if (!cfg.token) {
83
+ throw new Error("MCP_TOKEN is not set. Mint one at /admin/api-tokens on your deployment (see /admin/api-tokens/docs) and put it in the mcpServers env block.");
84
+ }
85
+ if (/[\r\n]/.test(cfg.token)) {
86
+ throw new Error("MCP_TOKEN contains a line break. Paste the token again so that it sits on one line, with nothing after it.");
87
+ }
88
+ }
package/dist/entry.js ADDED
@@ -0,0 +1,31 @@
1
+ // Is this module the program Node was asked to run?
2
+ //
3
+ // main() must run when the file is launched as a script and never when
4
+ // it is imported (the tests import buildServer). So the question is
5
+ // whether this module's file is the file named on the command line.
6
+ //
7
+ // Compare REAL paths. import.meta.url is the real path of the entry
8
+ // file, because Node follows symlinks before it loads an entry point.
9
+ // process.argv[1] is the path as it was typed, and for a command that npm
10
+ // installed (the global bin, or node_modules/.bin under npx) that is a
11
+ // SYMLINK to dist/index.js. Compared as `file://${process.argv[1]}`, the
12
+ // two never matched through a bin: main() did not run, and the process
13
+ // exited 0 without a word. That came in with PR #793 and was found in
14
+ // #7687. A URL string is also the wrong thing to compare: a directory
15
+ // with a space or a % in its name is percent-encoded in one and not in
16
+ // the other.
17
+ import { realpathSync } from "node:fs";
18
+ import { fileURLToPath } from "node:url";
19
+ export function isEntryPoint(moduleUrl, argv1 = process.argv[1]) {
20
+ if (!argv1)
21
+ return false;
22
+ try {
23
+ return realpathSync(fileURLToPath(moduleUrl)) === realpathSync(argv1);
24
+ }
25
+ catch {
26
+ // A module that is not a file (a data: URL), or an argv[1] that is
27
+ // not a path that exists (node -e, a REPL, a dangling link): this is
28
+ // not a launch of the script.
29
+ return false;
30
+ }
31
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,43 @@
1
+ // Typed error surface for the HTTP client.
2
+ //
3
+ // Every tool wraps its call in a try/catch and turns these into
4
+ // MCP tool errors so Claude sees a clear message instead of a raw
5
+ // exception stack.
6
+ // ShdEspApiError is the wire-level failure — the backend returned
7
+ // non-2xx. Carries the HTTP status + the parsed `error` field from
8
+ // the JSON body when present.
9
+ export class ShdEspApiError extends Error {
10
+ status;
11
+ path;
12
+ body;
13
+ constructor(status, path, message, body) {
14
+ super(`${status} ${path}: ${message}`);
15
+ this.name = "ShdEspApiError";
16
+ this.status = status;
17
+ this.path = path;
18
+ this.body = body;
19
+ }
20
+ }
21
+ // ShdEspTransportError is a network / timeout / DNS failure —
22
+ // nothing came back from the server at all.
23
+ export class ShdEspTransportError extends Error {
24
+ path;
25
+ cause;
26
+ constructor(path, message, cause) {
27
+ super(`transport error on ${path}: ${message}`);
28
+ this.name = "ShdEspTransportError";
29
+ this.path = path;
30
+ this.cause = cause;
31
+ }
32
+ }
33
+ // isTransientError is the retry-classification predicate. 429 +
34
+ // 5xx + transport failures are transient; everything else is a
35
+ // terminal error the caller should surface as-is.
36
+ export function isTransientError(err) {
37
+ if (err instanceof ShdEspTransportError)
38
+ return true;
39
+ if (err instanceof ShdEspApiError) {
40
+ return err.status === 429 || err.status >= 500;
41
+ }
42
+ return false;
43
+ }
package/dist/index.js ADDED
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env node
2
+ // Entry point for the MCP server.
3
+ //
4
+ // Runs over stdio, matching the way MCP clients (Claude Code
5
+ // primarily) spawn subprocess-mode servers. Every tool wraps its
6
+ // backend call in a try/catch that surfaces failures as MCP tool
7
+ // errors — the operator sees a clear "API returned 429 for …"
8
+ // inside their Claude session, not a stack trace in an obscure
9
+ // process log. A missing setting is reported once, at startup.
10
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
+ import { assertConfigured, legacyEnvNotice, loadConfig } from "./config.js";
13
+ import { createClient } from "./client.js";
14
+ import { isEntryPoint } from "./entry.js";
15
+ import { ShdEspApiError, ShdEspTransportError } from "./errors.js";
16
+ import { whoami, whoamiInput, whoamiDescription, } from "./tools/whoami.js";
17
+ import { listProjects, listProjectsInput, listProjectsDescription, getProject, getProjectInput, getProjectDescription, createProject, createProjectInput, createProjectDescription, } from "./tools/projects.js";
18
+ import { listTasks, listTasksInput, listTasksDescription, getTask, getTaskInput, getTaskDescription, createTask, createTaskInput, createTaskDescription, updateTask, updateTaskInput, updateTaskDescription, kanbanMoveTask, kanbanMoveTaskInput, kanbanMoveTaskDescription, archiveTask, archiveTaskInput, archiveTaskDescription, } from "./tools/tasks.js";
19
+ import { listContacts, listContactsInput, listContactsDescription, getContact, getContactInput, getContactDescription, createContact, createContactInput, createContactDescription, updateContact, updateContactInput, updateContactDescription, archiveContact, archiveContactInput, archiveContactDescription, listContactNotes, listContactNotesInput, listContactNotesDescription, addContactNote, addContactNoteInput, addContactNoteDescription, } from "./tools/contacts.js";
20
+ import { listAccounts, listAccountsInput, listAccountsDescription, getAccount, getAccountInput, getAccountDescription, createAccount, createAccountInput, createAccountDescription, updateAccount, updateAccountInput, updateAccountDescription, archiveAccount, archiveAccountInput, archiveAccountDescription, } from "./tools/accounts.js";
21
+ import { listDeals, listDealsInput, listDealsDescription, getDeal, getDealInput, getDealDescription, createDeal, createDealInput, createDealDescription, updateDeal, updateDealInput, updateDealDescription, moveDealToStage, moveDealToStageInput, moveDealToStageDescription, archiveDeal, archiveDealInput, archiveDealDescription, listDealNotes, listDealNotesInput, listDealNotesDescription, addDealNote, addDealNoteInput, addDealNoteDescription, } from "./tools/deals.js";
22
+ import { listNotifications, listNotificationsInput, listNotificationsDescription, getUnreadCount, getUnreadCountInput, getUnreadCountDescription, markNotificationRead, markNotificationReadInput, markNotificationReadDescription, waitForNotification, waitForNotificationInput, waitForNotificationDescription, } from "./tools/notifications.js";
23
+ // buildServer wires tools onto a fresh McpServer. Exported so
24
+ // tests can mount a stub client instead of a live HTTP one.
25
+ export function buildServer(client) {
26
+ const server = new McpServer(
27
+ // Keep the version in step with package.json and client.ts's
28
+ // User-Agent; tests/brand-surface-7687.test.ts fails on drift.
29
+ { name: "deredex-mcp", version: "0.4.0" }, { capabilities: { tools: {} } });
30
+ server.registerTool("whoami", { description: whoamiDescription, inputSchema: whoamiInput }, async () => callTool(() => whoami(client)));
31
+ server.registerTool("list_projects", { description: listProjectsDescription, inputSchema: listProjectsInput }, async (args) => callTool(() => listProjects(client, args)));
32
+ server.registerTool("get_project", { description: getProjectDescription, inputSchema: getProjectInput }, async (args) => callTool(() => getProject(client, args)));
33
+ server.registerTool("create_project", { description: createProjectDescription, inputSchema: createProjectInput }, async (args) => callTool(() => createProject(client, args)));
34
+ server.registerTool("list_tasks", { description: listTasksDescription, inputSchema: listTasksInput }, async (args) => callTool(() => listTasks(client, args)));
35
+ server.registerTool("get_task", { description: getTaskDescription, inputSchema: getTaskInput }, async (args) => callTool(() => getTask(client, args)));
36
+ server.registerTool("create_task", { description: createTaskDescription, inputSchema: createTaskInput }, async (args) => callTool(() => createTask(client, args)));
37
+ server.registerTool("update_task", { description: updateTaskDescription, inputSchema: updateTaskInput }, async (args) => callTool(() => updateTask(client, args)));
38
+ server.registerTool("kanban_move_task", {
39
+ description: kanbanMoveTaskDescription,
40
+ inputSchema: kanbanMoveTaskInput,
41
+ }, async (args) => callTool(() => kanbanMoveTask(client, args)));
42
+ server.registerTool("archive_task", { description: archiveTaskDescription, inputSchema: archiveTaskInput }, async (args) => callTool(() => archiveTask(client, args)));
43
+ // -- CRM contacts --
44
+ server.registerTool("list_contacts", { description: listContactsDescription, inputSchema: listContactsInput }, async (args) => callTool(() => listContacts(client, args)));
45
+ server.registerTool("get_contact", { description: getContactDescription, inputSchema: getContactInput }, async (args) => callTool(() => getContact(client, args)));
46
+ server.registerTool("create_contact", { description: createContactDescription, inputSchema: createContactInput }, async (args) => callTool(() => createContact(client, args)));
47
+ server.registerTool("update_contact", { description: updateContactDescription, inputSchema: updateContactInput }, async (args) => callTool(() => updateContact(client, args)));
48
+ server.registerTool("archive_contact", { description: archiveContactDescription, inputSchema: archiveContactInput }, async (args) => callTool(() => archiveContact(client, args)));
49
+ server.registerTool("list_contact_notes", { description: listContactNotesDescription, inputSchema: listContactNotesInput }, async (args) => callTool(() => listContactNotes(client, args)));
50
+ server.registerTool("add_contact_note", { description: addContactNoteDescription, inputSchema: addContactNoteInput }, async (args) => callTool(() => addContactNote(client, args)));
51
+ // -- CRM accounts --
52
+ server.registerTool("list_accounts", { description: listAccountsDescription, inputSchema: listAccountsInput }, async (args) => callTool(() => listAccounts(client, args)));
53
+ server.registerTool("get_account", { description: getAccountDescription, inputSchema: getAccountInput }, async (args) => callTool(() => getAccount(client, args)));
54
+ server.registerTool("create_account", { description: createAccountDescription, inputSchema: createAccountInput }, async (args) => callTool(() => createAccount(client, args)));
55
+ server.registerTool("update_account", { description: updateAccountDescription, inputSchema: updateAccountInput }, async (args) => callTool(() => updateAccount(client, args)));
56
+ server.registerTool("archive_account", { description: archiveAccountDescription, inputSchema: archiveAccountInput }, async (args) => callTool(() => archiveAccount(client, args)));
57
+ // -- CRM deals --
58
+ server.registerTool("list_deals", { description: listDealsDescription, inputSchema: listDealsInput }, async (args) => callTool(() => listDeals(client, args)));
59
+ server.registerTool("get_deal", { description: getDealDescription, inputSchema: getDealInput }, async (args) => callTool(() => getDeal(client, args)));
60
+ server.registerTool("create_deal", { description: createDealDescription, inputSchema: createDealInput }, async (args) => callTool(() => createDeal(client, args)));
61
+ server.registerTool("update_deal", { description: updateDealDescription, inputSchema: updateDealInput }, async (args) => callTool(() => updateDeal(client, args)));
62
+ server.registerTool("move_deal_to_stage", { description: moveDealToStageDescription, inputSchema: moveDealToStageInput }, async (args) => callTool(() => moveDealToStage(client, args)));
63
+ server.registerTool("archive_deal", { description: archiveDealDescription, inputSchema: archiveDealInput }, async (args) => callTool(() => archiveDeal(client, args)));
64
+ server.registerTool("list_deal_notes", { description: listDealNotesDescription, inputSchema: listDealNotesInput }, async (args) => callTool(() => listDealNotes(client, args)));
65
+ server.registerTool("add_deal_note", { description: addDealNoteDescription, inputSchema: addDealNoteInput }, async (args) => callTool(() => addDealNote(client, args)));
66
+ // -- Notifications (Trio 161 fork 1) --
67
+ server.registerTool("list_notifications", {
68
+ description: listNotificationsDescription,
69
+ inputSchema: listNotificationsInput,
70
+ }, async (args) => callTool(() => listNotifications(client, args)));
71
+ server.registerTool("get_unread_count", {
72
+ description: getUnreadCountDescription,
73
+ inputSchema: getUnreadCountInput,
74
+ }, async () => callTool(() => getUnreadCount(client)));
75
+ server.registerTool("mark_notification_read", {
76
+ description: markNotificationReadDescription,
77
+ inputSchema: markNotificationReadInput,
78
+ }, async (args) => callTool(() => markNotificationRead(client, args)));
79
+ server.registerTool("wait_for_notification", {
80
+ description: waitForNotificationDescription,
81
+ inputSchema: waitForNotificationInput,
82
+ }, async (args) => callTool(() => waitForNotification(client, args)));
83
+ return server;
84
+ }
85
+ // callTool is the uniform error-mapping wrapper. Turns every tool
86
+ // exception into a structured MCP tool result — the client sees
87
+ // isError=true + a clear textContent, not a process crash.
88
+ async function callTool(fn) {
89
+ try {
90
+ const value = await fn();
91
+ return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
92
+ }
93
+ catch (err) {
94
+ return { content: [{ type: "text", text: formatError(err) }], isError: true };
95
+ }
96
+ }
97
+ function formatError(err) {
98
+ if (err instanceof ShdEspApiError) {
99
+ return `API returned ${err.status} for ${err.path}: ${err.message.replace(/^\d+ \S+: /, "")}`;
100
+ }
101
+ if (err instanceof ShdEspTransportError) {
102
+ return `transport failure on ${err.path}: ${err.message}`;
103
+ }
104
+ if (err instanceof Error)
105
+ return err.message;
106
+ return String(err);
107
+ }
108
+ // main is the actual process entry point when this file is invoked
109
+ // as a script (`deredex-mcp` bin). Import-safe: pure buildServer()
110
+ // callers (tests) don't touch stdio.
111
+ async function main() {
112
+ const cfg = loadConfig();
113
+ // Fail-fast at startup with a clear message — we could defer this
114
+ // and per-tool errors, but the operator's first "hey Claude, use
115
+ // the platform" attempt is easier to diagnose when the process
116
+ // refuses to start on missing config instead of surfacing a
117
+ // per-tool 401.
118
+ try {
119
+ assertConfigured(cfg);
120
+ }
121
+ catch (err) {
122
+ process.stderr.write(`[deredex-mcp] startup error: ${err instanceof Error ? err.message : String(err)}\n`);
123
+ process.exit(1);
124
+ }
125
+ // stderr only: stdout carries the JSON-RPC traffic.
126
+ const notice = legacyEnvNotice();
127
+ if (notice)
128
+ process.stderr.write(`[deredex-mcp] notice: ${notice}\n`);
129
+ const client = createClient(cfg);
130
+ const server = buildServer(client);
131
+ const transport = new StdioServerTransport();
132
+ await server.connect(transport);
133
+ }
134
+ // Only run main when invoked as a script — never when imported for
135
+ // testing. isEntryPoint compares real paths: through an npm bin,
136
+ // process.argv[1] is the bin's symlink and import.meta.url is the file
137
+ // it points at (see entry.ts).
138
+ const isMain = isEntryPoint(import.meta.url);
139
+ if (isMain) {
140
+ main().catch((err) => {
141
+ process.stderr.write(`[deredex-mcp] fatal: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
142
+ process.exit(1);
143
+ });
144
+ }