@zanichelli/freshdesk-mcp 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +204 -2
- package/dist/cli.js +56 -0
- package/dist/client/errors.js +136 -0
- package/dist/client/http.js +389 -0
- package/dist/client/rate-limit.js +198 -0
- package/dist/client/resources/agents.js +15 -0
- package/dist/client/resources/canned.js +134 -0
- package/dist/client/resources/companies.js +57 -0
- package/dist/client/resources/contacts.js +63 -0
- package/dist/client/resources/groups.js +15 -0
- package/dist/client/resources/list-all.js +54 -0
- package/dist/client/resources/search.js +94 -0
- package/dist/client/resources/solutions.js +192 -0
- package/dist/client/resources/ticket-fields.js +62 -0
- package/dist/client/resources/tickets.js +204 -0
- package/dist/config.js +174 -0
- package/dist/schema/index.js +145 -0
- package/dist/schema/input.js +260 -0
- package/dist/schema/output.js +138 -0
- package/dist/server.js +31 -0
- package/dist/tools/budget.js +63 -0
- package/dist/tools/context.js +62 -0
- package/dist/tools/csv.js +35 -0
- package/dist/tools/format.js +191 -0
- package/dist/tools/list.js +130 -0
- package/dist/tools/rows.js +132 -0
- package/dist/tools/ticket-query.js +408 -0
- package/dist/tools/toolsets/core/canned.js +163 -0
- package/dist/tools/toolsets/core/count-tickets.js +602 -0
- package/dist/tools/toolsets/core/export-tickets.js +461 -0
- package/dist/tools/toolsets/core/find-similar-tickets.js +309 -0
- package/dist/tools/toolsets/core/get-ticket-schema.js +134 -0
- package/dist/tools/toolsets/core/get-ticket.js +280 -0
- package/dist/tools/toolsets/core/index.js +30 -0
- package/dist/tools/toolsets/core/list-agents.js +70 -0
- package/dist/tools/toolsets/core/list-groups.js +60 -0
- package/dist/tools/toolsets/core/list-tickets.js +210 -0
- package/dist/tools/toolsets/core/search-tickets.js +82 -0
- package/dist/tools/toolsets/core/solutions.js +282 -0
- package/dist/tools/toolsets/core/triage-queue.js +253 -0
- package/dist/tools/toolsets/index.js +110 -0
- package/dist/version.js +4 -0
- package/examples/team-config.example.json +20 -0
- package/package.json +38 -4
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Tickets (SPEC §7.1, §5): typed reads of tickets and their conversations,
|
|
2
|
+
// with the parameters docs/architecture/ticket-queries.md ("Parameters")
|
|
3
|
+
// chose. Search is T-024's.
|
|
4
|
+
//
|
|
5
|
+
// - `listTickets`: one page of `GET /tickets`, and whether another exists
|
|
6
|
+
// (a `Link` to it). It sends `per_page` (100 unless given) and only the
|
|
7
|
+
// other parameters given, field by field: no `updated_since` unless asked,
|
|
8
|
+
// since `requester_id` alone lifts the 30-day window (measured 2026-11-24).
|
|
9
|
+
// - `getTicket`: `GET /tickets/{id}`, with `include=stats` when asked. No
|
|
10
|
+
// other include: a requester's or a company's data comes from T-025's
|
|
11
|
+
// contact and company reads, which drop what no tool should return.
|
|
12
|
+
// `stats` is passed through unchecked: its reader checks it.
|
|
13
|
+
// - `listConversations`: every page of `GET /tickets/{id}/conversations`,
|
|
14
|
+
// through `list-all.ts`: 100 per page, at most 10 pages, `truncated`; a
|
|
15
|
+
// failed request carries `attempts`.
|
|
16
|
+
// - `listConversationPage`: its first page alone (the oldest 100), and
|
|
17
|
+
// whether another exists; for a caller bounded to one request a ticket
|
|
18
|
+
// (`find_similar_tickets`' excerpt, T-030). Its failures, a malformed
|
|
19
|
+
// page included, carry `attempts`.
|
|
20
|
+
//
|
|
21
|
+
// A ticket needs a whole-number `id`, `requester_id`, `status` and
|
|
22
|
+
// `priority`, a string `subject` and a `custom_fields` object; a conversation
|
|
23
|
+
// a whole-number `id` and `user_id`, a string `body`, booleans `incoming` and
|
|
24
|
+
// `private`. Keys this module does not know are passed through. A body in any
|
|
25
|
+
// other shape is `server` with the response's real status, not retryable,
|
|
26
|
+
// and a message of fixed text that quotes nothing from the body. An HTTP
|
|
27
|
+
// failure is returned unchanged.
|
|
28
|
+
//
|
|
29
|
+
// Values are checked before anything is sent, whatever a cast let through:
|
|
30
|
+
// an id is a positive safe integer, `per_page` 1–100, `page` a whole number
|
|
31
|
+
// from 1, `order_by`, `order_type` and an include in their sets. Any other
|
|
32
|
+
// is `validation` with `http_status: null`, naming the parameter, not the
|
|
33
|
+
// value, and no request is sent.
|
|
34
|
+
//
|
|
35
|
+
// `attempts` is the requests sent, retries included: what a tool reports as
|
|
36
|
+
// API calls. `deadline` (epoch ms, optional) is the caller's: see
|
|
37
|
+
// `requestWithRetry` and `paginate`.
|
|
38
|
+
//
|
|
39
|
+
// Cost class: `cheap`, except a `listTickets` page, a `getTicket` view, a
|
|
40
|
+
// `listConversations` or a `listConversationPage` page whose caller gives
|
|
41
|
+
// `expensive` (a scan, `triage_queue`'s view per row, `find_similar_tickets`,
|
|
42
|
+
// `export_tickets`' threads:
|
|
43
|
+
// docs/architecture/ticket-queries.md, "Cost class for the limiter"). A
|
|
44
|
+
// `listTickets` page, a `getTicket` view or a `listConversationPage` page
|
|
45
|
+
// that fails after its values were accepted carries `attempts` too: the
|
|
46
|
+
// requests sent for it, 0 when the limiter refused it before any.
|
|
47
|
+
import { z } from "zod";
|
|
48
|
+
import { listAll, PER_PAGE } from "./list-all.js";
|
|
49
|
+
/** A ticket as a list, a view and a search result carry it. */
|
|
50
|
+
export const ticket = z.looseObject({
|
|
51
|
+
id: z.number().int(),
|
|
52
|
+
subject: z.string(),
|
|
53
|
+
status: z.number().int(),
|
|
54
|
+
priority: z.number().int(),
|
|
55
|
+
requester_id: z.number().int(),
|
|
56
|
+
custom_fields: z.record(z.string(), z.unknown()),
|
|
57
|
+
});
|
|
58
|
+
const conversation = z.looseObject({
|
|
59
|
+
id: z.number().int(),
|
|
60
|
+
user_id: z.number().int(),
|
|
61
|
+
body: z.string(),
|
|
62
|
+
incoming: z.boolean(),
|
|
63
|
+
private: z.boolean(),
|
|
64
|
+
});
|
|
65
|
+
/** Freshdesk returns no page of `GET /tickets` past this one (30,000 tickets at 100 a page). */
|
|
66
|
+
export const MAX_LIST_PAGE = 300;
|
|
67
|
+
const ORDER_BY = new Set(["created_at", "due_by", "updated_at", "status"]);
|
|
68
|
+
const ORDER_TYPE = new Set(["asc", "desc"]);
|
|
69
|
+
const OPTIONAL = [
|
|
70
|
+
"page",
|
|
71
|
+
"updated_since",
|
|
72
|
+
"order_by",
|
|
73
|
+
"order_type",
|
|
74
|
+
"include",
|
|
75
|
+
"requester_id",
|
|
76
|
+
"company_id",
|
|
77
|
+
];
|
|
78
|
+
export async function listTickets(http, options = {}, deadline, cost) {
|
|
79
|
+
const { per_page, page, order_by, order_type, include, requester_id, company_id } = options;
|
|
80
|
+
if (per_page !== undefined && !(isPositiveInt(per_page) && per_page <= PER_PAGE)) {
|
|
81
|
+
return refused("per_page");
|
|
82
|
+
}
|
|
83
|
+
if (page !== undefined && !isPositiveInt(page))
|
|
84
|
+
return refused("page");
|
|
85
|
+
if (order_by !== undefined && !ORDER_BY.has(order_by))
|
|
86
|
+
return refused("order_by");
|
|
87
|
+
if (order_type !== undefined && !ORDER_TYPE.has(order_type))
|
|
88
|
+
return refused("order_type");
|
|
89
|
+
if (include !== undefined && include !== "stats")
|
|
90
|
+
return refused("include");
|
|
91
|
+
if (requester_id !== undefined && !isPositiveInt(requester_id))
|
|
92
|
+
return refused("requester_id");
|
|
93
|
+
if (company_id !== undefined && !isPositiveInt(company_id))
|
|
94
|
+
return refused("company_id");
|
|
95
|
+
const query = { per_page: options.per_page ?? PER_PAGE };
|
|
96
|
+
for (const name of OPTIONAL) {
|
|
97
|
+
const value = options[name];
|
|
98
|
+
if (value !== undefined)
|
|
99
|
+
query[name] = value;
|
|
100
|
+
}
|
|
101
|
+
const pages = http.paginate({ path: "/tickets", query, ...(cost === undefined ? {} : { cost }) }, { pages: 1 }, deadline);
|
|
102
|
+
let tickets = [];
|
|
103
|
+
for (;;) {
|
|
104
|
+
// By hand, not `for await`: the return value is where `truncated` is.
|
|
105
|
+
const step = await pages.next();
|
|
106
|
+
if (step.done) {
|
|
107
|
+
// One page asked for: `truncated` is a `Link` to the next one.
|
|
108
|
+
const { truncated, attempts } = step.value;
|
|
109
|
+
return { ok: true, tickets, has_more: truncated, attempts };
|
|
110
|
+
}
|
|
111
|
+
const result = step.value;
|
|
112
|
+
if (!result.ok) {
|
|
113
|
+
// A failed page ends the iteration: its return value has the count.
|
|
114
|
+
const end = await pages.next();
|
|
115
|
+
return { ...result, attempts: end.done ? end.value.attempts : 0 };
|
|
116
|
+
}
|
|
117
|
+
const parsed = ticket.array().safeParse(result.body);
|
|
118
|
+
if (!parsed.success)
|
|
119
|
+
return malformed("tickets", result.status);
|
|
120
|
+
tickets = parsed.data;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export async function getTicket(http, id, include = [], deadline, cost) {
|
|
124
|
+
if (!isPositiveInt(id))
|
|
125
|
+
return refused("id");
|
|
126
|
+
if (!include.every((name) => name === "stats"))
|
|
127
|
+
return refused("include");
|
|
128
|
+
const result = await http.requestWithRetry({
|
|
129
|
+
path: "/tickets/{id}",
|
|
130
|
+
params: { id },
|
|
131
|
+
...(include.length === 0 ? {} : { query: { include: include.join(",") } }),
|
|
132
|
+
...(cost === undefined ? {} : { cost }),
|
|
133
|
+
}, deadline);
|
|
134
|
+
if (!result.ok)
|
|
135
|
+
return { ok: false, error: result.error, attempts: result.attempts };
|
|
136
|
+
const parsed = ticket.safeParse(result.body);
|
|
137
|
+
if (!parsed.success)
|
|
138
|
+
return malformed("a ticket", result.status);
|
|
139
|
+
return { ok: true, ticket: parsed.data, attempts: result.attempts };
|
|
140
|
+
}
|
|
141
|
+
export function listConversations(http, ticketId, deadline, cost) {
|
|
142
|
+
if (!isPositiveInt(ticketId))
|
|
143
|
+
return Promise.resolve(refused("ticket id"));
|
|
144
|
+
return listAll(http, "/tickets/{id}/conversations", conversation, "conversations", deadline, { id: ticketId }, cost);
|
|
145
|
+
}
|
|
146
|
+
export async function listConversationPage(http, ticketId, deadline, cost) {
|
|
147
|
+
if (!isPositiveInt(ticketId))
|
|
148
|
+
return refused("ticket id");
|
|
149
|
+
const pages = http.paginate({
|
|
150
|
+
path: "/tickets/{id}/conversations",
|
|
151
|
+
params: { id: ticketId },
|
|
152
|
+
query: { per_page: PER_PAGE },
|
|
153
|
+
...(cost === undefined ? {} : { cost }),
|
|
154
|
+
}, { pages: 1 }, deadline);
|
|
155
|
+
let conversations = [];
|
|
156
|
+
for (;;) {
|
|
157
|
+
// By hand, not `for await`: the return value is where `truncated` is.
|
|
158
|
+
const step = await pages.next();
|
|
159
|
+
if (step.done) {
|
|
160
|
+
const { truncated, attempts } = step.value;
|
|
161
|
+
return { ok: true, conversations, has_more: truncated, attempts };
|
|
162
|
+
}
|
|
163
|
+
const result = step.value;
|
|
164
|
+
if (!result.ok) {
|
|
165
|
+
const end = await pages.next();
|
|
166
|
+
return { ...result, attempts: end.done ? end.value.attempts : 0 };
|
|
167
|
+
}
|
|
168
|
+
const parsed = conversation.array().safeParse(result.body);
|
|
169
|
+
if (!parsed.success) {
|
|
170
|
+
// One page asked for: the next step ends the iteration with the count.
|
|
171
|
+
const end = await pages.next();
|
|
172
|
+
return {
|
|
173
|
+
...malformed("conversations", result.status),
|
|
174
|
+
attempts: end.done ? end.value.attempts : 0,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
conversations = parsed.data;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function malformed(noun, status) {
|
|
181
|
+
return {
|
|
182
|
+
ok: false,
|
|
183
|
+
error: {
|
|
184
|
+
code: "server",
|
|
185
|
+
http_status: status,
|
|
186
|
+
message: `Freshdesk sent ${noun} in an unexpected shape (HTTP ${status}).`,
|
|
187
|
+
retryable: false,
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function isPositiveInt(value) {
|
|
192
|
+
return Number.isSafeInteger(value) && value > 0;
|
|
193
|
+
}
|
|
194
|
+
function refused(name) {
|
|
195
|
+
return {
|
|
196
|
+
ok: false,
|
|
197
|
+
error: {
|
|
198
|
+
code: "validation",
|
|
199
|
+
http_status: null,
|
|
200
|
+
message: `Not sent: ${name} is not a valid value.`,
|
|
201
|
+
retryable: false,
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Configuration (SPEC §10): personal settings from the environment, team
|
|
2
|
+
// settings from an optional JSON file.
|
|
3
|
+
//
|
|
4
|
+
// Personal (env):
|
|
5
|
+
// FRESHDESK_DOMAIN, FRESHDESK_API_KEY required
|
|
6
|
+
// FRESHDESK_MCP_CONFIG path of the team file, optional
|
|
7
|
+
// FRESHDESK_HOST_OVERRIDE one exact hostname, optional
|
|
8
|
+
// FRESHDESK_EXPORT_DIR export_tickets' directory, optional
|
|
9
|
+
// The override is personal on purpose: a shared team file must not be able
|
|
10
|
+
// to point everyone's API key at another host, so the team schema has no
|
|
11
|
+
// such key and refuses unknown ones. The export directory is personal too
|
|
12
|
+
// (owner, 2026-11-23): a shared file does not choose a local path, and a team
|
|
13
|
+
// file that still carries `export_dir` is refused as an unknown key. Whether
|
|
14
|
+
// the directory is usable (absolute, existing, not a symlink) is checked by
|
|
15
|
+
// `export_tickets` when it runs, not here: unset, only that tool is refused.
|
|
16
|
+
//
|
|
17
|
+
// This module checks presence and types, plus the override's shape (one
|
|
18
|
+
// lower-case dotted hostname, see isHostname). Whether the domain or the
|
|
19
|
+
// override is an acceptable host to send the key to is the HTTP client's
|
|
20
|
+
// rule (SPEC §7.1), checked there at construction and per request.
|
|
21
|
+
//
|
|
22
|
+
// A ConfigError's message names the variable, or the file's path and the
|
|
23
|
+
// key path inside it. It quotes no value from the environment or the file
|
|
24
|
+
// (which may not be the file the user meant), with two exceptions it needs
|
|
25
|
+
// to be useful: the FRESHDESK_MCP_CONFIG path and the file's key names.
|
|
26
|
+
// Wherever the API key's text would appear in either, it is replaced.
|
|
27
|
+
import { readFileSync } from "node:fs";
|
|
28
|
+
import { z } from "zod";
|
|
29
|
+
export class ConfigError extends Error {
|
|
30
|
+
name = "ConfigError";
|
|
31
|
+
}
|
|
32
|
+
const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
|
|
33
|
+
const HOSTNAME = new RegExp(`^(?:${LABEL}\\.)+${LABEL}$`);
|
|
34
|
+
/**
|
|
35
|
+
* A lower-case, dotted DNS name: no scheme, port, path, wildcard or IP.
|
|
36
|
+
* The last label starts with a letter, so no spelling of an IPv4 address
|
|
37
|
+
* that a URL parser accepts (`1.2.3.4`, `1.2.3.0x4`) passes.
|
|
38
|
+
*/
|
|
39
|
+
function isHostname(value) {
|
|
40
|
+
return value.length <= 253 && HOSTNAME.test(value) && /\.[a-z][a-z0-9-]*$/.test(value);
|
|
41
|
+
}
|
|
42
|
+
const required = (name) => z.string({ error: `${name} is required` }).min(1, `${name} is required`);
|
|
43
|
+
const envSchema = z.object({
|
|
44
|
+
FRESHDESK_DOMAIN: required("FRESHDESK_DOMAIN"),
|
|
45
|
+
FRESHDESK_API_KEY: required("FRESHDESK_API_KEY"),
|
|
46
|
+
FRESHDESK_MCP_CONFIG: z.string().optional(),
|
|
47
|
+
FRESHDESK_HOST_OVERRIDE: z
|
|
48
|
+
.string()
|
|
49
|
+
.refine(isHostname, {
|
|
50
|
+
error: "FRESHDESK_HOST_OVERRIDE must be one lower-case hostname (like support.example.com): no scheme, port, path or wildcard",
|
|
51
|
+
})
|
|
52
|
+
.optional(),
|
|
53
|
+
FRESHDESK_EXPORT_DIR: z.string().optional(),
|
|
54
|
+
});
|
|
55
|
+
const percent = z.number().min(0).max(100);
|
|
56
|
+
const teamSchema = z.strictObject({
|
|
57
|
+
/** Enabled toolsets (SPEC §8.1). */
|
|
58
|
+
toolsets: z
|
|
59
|
+
.array(z.enum(["core", "write", "send"]))
|
|
60
|
+
.min(1)
|
|
61
|
+
.default(["core"]),
|
|
62
|
+
/** Per ticket field, keyed by label or API name (SPEC §7.3). */
|
|
63
|
+
fields: z
|
|
64
|
+
.record(z.string().min(1), z.strictObject({
|
|
65
|
+
/** Text telling the model what the field means. */
|
|
66
|
+
meaning: z.string().min(1).optional(),
|
|
67
|
+
/**
|
|
68
|
+
* Left out of a ticket's detail output (personal data). Not an access
|
|
69
|
+
* control: not applied to the schema tool, to queries or to input, and
|
|
70
|
+
* not guaranteed in rows, counts or exports (SPEC §7.3).
|
|
71
|
+
*/
|
|
72
|
+
hidden: z.boolean().default(false),
|
|
73
|
+
}))
|
|
74
|
+
.default({}),
|
|
75
|
+
/** A ticket is uncategorised when these are empty. Absent: the default rule of SPEC §10. */
|
|
76
|
+
uncategorised_fields: z.array(z.string().min(1)).min(1).optional(),
|
|
77
|
+
/** Who `forward_ticket` may write to: `@domain` or a full address. */
|
|
78
|
+
forward_allow_list: z
|
|
79
|
+
.array(z.string().regex(/^[^@\s]*@[^@\s]+$/, 'expected "@domain" or a full address'))
|
|
80
|
+
.default([]),
|
|
81
|
+
limits: z
|
|
82
|
+
.strictObject({
|
|
83
|
+
/** Below this share of the rate-limit window, expensive operations are refused. */
|
|
84
|
+
reserve_pct: percent.default(20),
|
|
85
|
+
/** Below this share, everything waits or fails fast. */
|
|
86
|
+
floor_pct: percent.default(5),
|
|
87
|
+
/** Pacing of expensive operations, requests per second. */
|
|
88
|
+
pacing_rps: z.number().positive().default(2),
|
|
89
|
+
/** Most tickets one bulk call may change. */
|
|
90
|
+
bulk_cap: z.int().positive().default(50),
|
|
91
|
+
/** How long the ticket-field schema is cached, seconds. */
|
|
92
|
+
schema_ttl_s: z.int().positive().default(3600),
|
|
93
|
+
/** Most API calls one tool call may estimate before it needs `confirm: true` (SPEC §7.2). */
|
|
94
|
+
call_budget: z.int().positive().default(250),
|
|
95
|
+
})
|
|
96
|
+
.refine((limits) => limits.floor_pct <= limits.reserve_pct, {
|
|
97
|
+
path: ["floor_pct"],
|
|
98
|
+
error: "must not be above reserve_pct",
|
|
99
|
+
})
|
|
100
|
+
.prefault({}),
|
|
101
|
+
});
|
|
102
|
+
/** One line per problem: `"path.to.key": what is wrong`. Never the value. */
|
|
103
|
+
function describeIssues(issues) {
|
|
104
|
+
return issues.flatMap((issue) => {
|
|
105
|
+
const at = (path) => `"${path.map(String).join(".")}"`;
|
|
106
|
+
if (issue.code === "unrecognized_keys") {
|
|
107
|
+
return issue.keys.map((key) => `${at([...issue.path, key])}: unknown key`);
|
|
108
|
+
}
|
|
109
|
+
return [`${issue.path.length === 0 ? "the file" : at(issue.path)}: ${issue.message}`];
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
function loadTeamConfig(path) {
|
|
113
|
+
if (path === undefined)
|
|
114
|
+
return teamSchema.parse({});
|
|
115
|
+
let text;
|
|
116
|
+
try {
|
|
117
|
+
text = readFileSync(path, "utf8");
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
// No `cause`, here and below: its text may quote the file. Only a
|
|
121
|
+
// Node error code (ENOENT, EACCES, EISDIR) is passed on.
|
|
122
|
+
const code = /^E[A-Z]+$/.exec(String(err.code))?.[0];
|
|
123
|
+
throw new ConfigError(`Cannot read the team config ${path} (FRESHDESK_MCP_CONFIG)${code ? `: ${code}` : ""}.`);
|
|
124
|
+
}
|
|
125
|
+
let json;
|
|
126
|
+
try {
|
|
127
|
+
json = JSON.parse(text);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
throw new ConfigError(`The team config ${path} is not valid JSON.`);
|
|
131
|
+
}
|
|
132
|
+
const parsed = teamSchema.safeParse(json);
|
|
133
|
+
if (!parsed.success) {
|
|
134
|
+
throw new ConfigError([`Invalid team config ${path}:`, ...describeIssues(parsed.error.issues)].join("\n "));
|
|
135
|
+
}
|
|
136
|
+
return parsed.data;
|
|
137
|
+
}
|
|
138
|
+
/** Load and validate the configuration. Throws `ConfigError`. */
|
|
139
|
+
export function loadConfig(env) {
|
|
140
|
+
// An MCP client may pass an unset optional setting as an empty string.
|
|
141
|
+
const parsed = envSchema.safeParse({
|
|
142
|
+
FRESHDESK_DOMAIN: env.FRESHDESK_DOMAIN,
|
|
143
|
+
FRESHDESK_API_KEY: env.FRESHDESK_API_KEY,
|
|
144
|
+
FRESHDESK_MCP_CONFIG: env.FRESHDESK_MCP_CONFIG || undefined,
|
|
145
|
+
FRESHDESK_HOST_OVERRIDE: env.FRESHDESK_HOST_OVERRIDE || undefined,
|
|
146
|
+
FRESHDESK_EXPORT_DIR: env.FRESHDESK_EXPORT_DIR || undefined,
|
|
147
|
+
});
|
|
148
|
+
if (!parsed.success) {
|
|
149
|
+
throw new ConfigError(["Invalid environment:", ...parsed.error.issues.map((issue) => issue.message)].join("\n "));
|
|
150
|
+
}
|
|
151
|
+
const personal = parsed.data;
|
|
152
|
+
let team;
|
|
153
|
+
try {
|
|
154
|
+
team = loadTeamConfig(personal.FRESHDESK_MCP_CONFIG);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
// The path and the file's key names are quoted: a key pasted into the
|
|
158
|
+
// wrong setting, or a wrong file, must not put the API key in a message.
|
|
159
|
+
if (!(err instanceof ConfigError))
|
|
160
|
+
throw err;
|
|
161
|
+
throw new ConfigError(err.message.replaceAll(personal.FRESHDESK_API_KEY, "[FRESHDESK_API_KEY]"));
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
domain: personal.FRESHDESK_DOMAIN,
|
|
165
|
+
apiKey: personal.FRESHDESK_API_KEY,
|
|
166
|
+
...(personal.FRESHDESK_HOST_OVERRIDE === undefined
|
|
167
|
+
? {}
|
|
168
|
+
: { hostOverride: personal.FRESHDESK_HOST_OVERRIDE }),
|
|
169
|
+
...(personal.FRESHDESK_EXPORT_DIR === undefined
|
|
170
|
+
? {}
|
|
171
|
+
: { exportDir: personal.FRESHDESK_EXPORT_DIR }),
|
|
172
|
+
team,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Schema service (SPEC §7.3): the ticket fields, plus agents and groups as
|
|
2
|
+
// id → name maps, loaded together and kept for a TTL in seconds the caller
|
|
3
|
+
// gives (the team config's `limits.schema_ttl_s`, default 1 h, wired in
|
|
4
|
+
// src/tools/context.ts).
|
|
5
|
+
//
|
|
6
|
+
// - One load per TTL: the TTL runs from the moment the load started. Calls
|
|
7
|
+
// made while a load is in flight share it. A clock that went back before
|
|
8
|
+
// the load started counts as expired.
|
|
9
|
+
// - Every caller gets the same schema, so it is read-only: typed so, and
|
|
10
|
+
// frozen deep. The name maps are a `FrozenMap`, which has no method
|
|
11
|
+
// that changes it, since freezing a Map does not stop its `set`.
|
|
12
|
+
// - A failed load is not cached: its error is returned unchanged and the
|
|
13
|
+
// next call loads again. The lists are read one after the other and the
|
|
14
|
+
// first failure stops the load.
|
|
15
|
+
// - A load ends within LOAD_DEADLINE_MS, its three lists together: every
|
|
16
|
+
// request carries the one deadline (see `requestWithRetry`), so at it the
|
|
17
|
+
// request in flight is cut and no other is started. The error is the
|
|
18
|
+
// client's: `network`, retryable, or `rate_limited` for a limiter wait
|
|
19
|
+
// that would reach it. Like any failed load, it is not cached.
|
|
20
|
+
// - `attempts` on a loaded result is the requests that load sent, retries
|
|
21
|
+
// included (the three lists' `attempts` added up), for the one call that
|
|
22
|
+
// started the load: what a tool adds to its `api_calls_used`. A call
|
|
23
|
+
// served from the cache, or joining a load in flight, gets 0, so a load's
|
|
24
|
+
// requests are counted once whoever reports them. A failed load reports
|
|
25
|
+
// none, as the lists it reads report none on failure.
|
|
26
|
+
// - Every result handed out is frozen, a failed one with its error: the
|
|
27
|
+
// load's result is shared with the calls that joined it, so the call
|
|
28
|
+
// that started it cannot swap the schema or the error they get.
|
|
29
|
+
// - Of an agent only the id and the name are kept: the contact's personal
|
|
30
|
+
// data (email, phone) is dropped here.
|
|
31
|
+
// - `truncated` is carried from the list: an id missing from a truncated
|
|
32
|
+
// list is "not loaded", not "unknown" (see output.ts).
|
|
33
|
+
import { listAgents } from "../client/resources/agents.js";
|
|
34
|
+
import { listGroups } from "../client/resources/groups.js";
|
|
35
|
+
import { listTicketFields } from "../client/resources/ticket-fields.js";
|
|
36
|
+
/**
|
|
37
|
+
* A read-only view of a Map. The Map is a private field: a caller that casts
|
|
38
|
+
* the view to `Map` finds no `set`, and `Map.prototype.set` refuses it.
|
|
39
|
+
*/
|
|
40
|
+
export class FrozenMap {
|
|
41
|
+
#map;
|
|
42
|
+
constructor(entries) {
|
|
43
|
+
this.#map = new Map(entries);
|
|
44
|
+
}
|
|
45
|
+
get size() {
|
|
46
|
+
return this.#map.size;
|
|
47
|
+
}
|
|
48
|
+
get(key) {
|
|
49
|
+
return this.#map.get(key);
|
|
50
|
+
}
|
|
51
|
+
has(key) {
|
|
52
|
+
return this.#map.has(key);
|
|
53
|
+
}
|
|
54
|
+
forEach(callback, thisArg) {
|
|
55
|
+
this.#map.forEach((value, key) => {
|
|
56
|
+
callback.call(thisArg, value, key, this);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
entries() {
|
|
60
|
+
return this.#map.entries();
|
|
61
|
+
}
|
|
62
|
+
keys() {
|
|
63
|
+
return this.#map.keys();
|
|
64
|
+
}
|
|
65
|
+
values() {
|
|
66
|
+
return this.#map.values();
|
|
67
|
+
}
|
|
68
|
+
[Symbol.iterator]() {
|
|
69
|
+
return this.#map.entries();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
// The class and its prototype too: no one swaps `get` for every view.
|
|
73
|
+
Object.freeze(FrozenMap.prototype);
|
|
74
|
+
Object.freeze(FrozenMap);
|
|
75
|
+
export function deepFreeze(value) {
|
|
76
|
+
if (typeof value === "object" && value !== null) {
|
|
77
|
+
for (const inner of Object.values(value))
|
|
78
|
+
deepFreeze(inner);
|
|
79
|
+
Object.freeze(value);
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
/** Longest one load may take, ticket fields, agents and groups together. */
|
|
84
|
+
export const LOAD_DEADLINE_MS = 30_000;
|
|
85
|
+
export class SchemaService {
|
|
86
|
+
// Real private members, and the instance frozen at the end of the
|
|
87
|
+
// constructor: a tool's mistake or a cast cannot drop the cache, plant a
|
|
88
|
+
// load or change the TTL (it gets a TypeError). Not claimed: hostile code
|
|
89
|
+
// in the process.
|
|
90
|
+
#cached;
|
|
91
|
+
#inFlight;
|
|
92
|
+
#ttlS;
|
|
93
|
+
#http;
|
|
94
|
+
constructor(http, ttlS) {
|
|
95
|
+
this.#http = http;
|
|
96
|
+
this.#ttlS = ttlS;
|
|
97
|
+
Object.freeze(this);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The cached schema while its TTL lasts; otherwise a new load. `attempts`
|
|
101
|
+
* is the load's requests for the call that started it, 0 for any other.
|
|
102
|
+
*/
|
|
103
|
+
get() {
|
|
104
|
+
const age = this.#cached ? Date.now() - this.#cached.loadedAt : -1;
|
|
105
|
+
if (this.#cached && age >= 0 && age < this.#ttlS * 1000) {
|
|
106
|
+
return Promise.resolve(Object.freeze({ ok: true, schema: this.#cached.schema, attempts: 0 }));
|
|
107
|
+
}
|
|
108
|
+
if (this.#inFlight) {
|
|
109
|
+
return this.#inFlight.then((result) => result.ok ? Object.freeze({ ...result, attempts: 0 }) : result);
|
|
110
|
+
}
|
|
111
|
+
this.#inFlight = this.#load()
|
|
112
|
+
.then(deepFreeze)
|
|
113
|
+
.finally(() => {
|
|
114
|
+
this.#inFlight = undefined;
|
|
115
|
+
});
|
|
116
|
+
return this.#inFlight;
|
|
117
|
+
}
|
|
118
|
+
async #load() {
|
|
119
|
+
const startedAt = Date.now();
|
|
120
|
+
const deadline = startedAt + LOAD_DEADLINE_MS;
|
|
121
|
+
const fields = await listTicketFields(this.#http, deadline);
|
|
122
|
+
if (!fields.ok)
|
|
123
|
+
return fields;
|
|
124
|
+
// A failed list's `attempts` is dropped: a failed load reports none.
|
|
125
|
+
const agents = await listAgents(this.#http, deadline);
|
|
126
|
+
if (!agents.ok)
|
|
127
|
+
return { ok: false, error: agents.error };
|
|
128
|
+
const groups = await listGroups(this.#http, deadline);
|
|
129
|
+
if (!groups.ok)
|
|
130
|
+
return { ok: false, error: groups.error };
|
|
131
|
+
const schema = deepFreeze({
|
|
132
|
+
fields: fields.fields,
|
|
133
|
+
agents: {
|
|
134
|
+
names: new FrozenMap(agents.items.map((agent) => [agent.id, agent.contact.name])),
|
|
135
|
+
truncated: agents.truncated,
|
|
136
|
+
},
|
|
137
|
+
groups: {
|
|
138
|
+
names: new FrozenMap(groups.items.map((group) => [group.id, group.name])),
|
|
139
|
+
truncated: groups.truncated,
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
this.#cached = { schema, loadedAt: startedAt };
|
|
143
|
+
return { ok: true, schema, attempts: fields.attempts + agents.attempts + groups.attempts };
|
|
144
|
+
}
|
|
145
|
+
}
|