@teamnetwork-nz/teamlink-mcp-server 0.5.8 → 0.6.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.
@@ -0,0 +1,83 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import http from "node:http";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ const loopback = new Set(["127.0.0.1", "::1", "localhost"]);
5
+ const send = (res, status, body) => {
6
+ res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
7
+ };
8
+ const error = (res, status, code, message) => send(res, status, { jsonrpc: "2.0", error: { code, message }, id: null });
9
+ const matches = (value, expected) => {
10
+ if (!value?.startsWith("Bearer "))
11
+ return false;
12
+ const supplied = Buffer.from(value.slice(7));
13
+ const wanted = Buffer.from(expected);
14
+ return supplied.length === wanted.length && timingSafeEqual(supplied, wanted);
15
+ };
16
+ const readBody = (req, limit) => new Promise((resolve, reject) => {
17
+ const chunks = [];
18
+ let size = 0;
19
+ let oversized = false;
20
+ req.on("data", (chunk) => { size += chunk.length; oversized ||= size > limit; if (!oversized)
21
+ chunks.push(chunk); });
22
+ req.on("end", () => {
23
+ if (oversized)
24
+ return reject(Object.assign(new Error("Request body too large"), { statusCode: 413 }));
25
+ try {
26
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
27
+ }
28
+ catch {
29
+ reject(Object.assign(new Error("Invalid JSON body"), { statusCode: 400 }));
30
+ }
31
+ });
32
+ req.on("error", reject);
33
+ });
34
+ export function validateHttpOptions(o) {
35
+ if (!Number.isInteger(o.port) || o.port < 1 || o.port > 65535)
36
+ throw new Error(`Invalid HTTP port: ${o.port}`);
37
+ if (o.maxBodyBytes !== undefined && (!Number.isInteger(o.maxBodyBytes) || o.maxBodyBytes < 1))
38
+ throw new Error(`Invalid HTTP body limit: ${o.maxBodyBytes}`);
39
+ if (!loopback.has(o.host) && !o.bearerToken)
40
+ throw new Error("A bearer token is required when binding beyond loopback");
41
+ if (!loopback.has(o.host) && !o.allowedHosts?.length)
42
+ throw new Error("HTTP_ALLOWED_HOSTS is required when binding beyond loopback");
43
+ }
44
+ export function createHttpServer(factory, o) {
45
+ validateHttpOptions(o);
46
+ const hosts = new Set(o.allowedHosts?.map(v => v.toLowerCase()));
47
+ const origins = new Set(o.allowedOrigins?.map(v => v.toLowerCase()));
48
+ return http.createServer(async (req, res) => {
49
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
50
+ if (path === "/health")
51
+ return send(res, 200, { status: "ok", server: o.serverName });
52
+ if (path !== "/mcp")
53
+ return void res.writeHead(404).end();
54
+ if (hosts.size && !hosts.has((req.headers.host ?? "").toLowerCase()))
55
+ return error(res, 403, -32000, "Host not allowed");
56
+ if (req.headers.origin && !origins.has(req.headers.origin.toLowerCase()))
57
+ return error(res, 403, -32000, "Origin not allowed");
58
+ if (o.bearerToken && !matches(req.headers.authorization, o.bearerToken)) {
59
+ res.setHeader("WWW-Authenticate", "Bearer");
60
+ return error(res, 401, -32001, "Unauthorized");
61
+ }
62
+ if (req.method !== "POST") {
63
+ res.setHeader("Allow", "POST");
64
+ return error(res, 405, -32000, "Method not allowed");
65
+ }
66
+ const server = factory();
67
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
68
+ try {
69
+ const body = await readBody(req, o.maxBodyBytes ?? 1048576);
70
+ await server.connect(transport);
71
+ await transport.handleRequest(req, res, body);
72
+ res.once("close", () => { void transport.close(); void server.close(); });
73
+ }
74
+ catch (cause) {
75
+ void transport.close();
76
+ void server.close();
77
+ if (!res.headersSent) {
78
+ const status = cause.statusCode ?? 500;
79
+ error(res, status, status === 400 ? -32700 : -32603, status < 500 ? cause.message : "Internal server error");
80
+ }
81
+ }
82
+ });
83
+ }
package/build/index.js CHANGED
@@ -7,6 +7,7 @@ import axios from 'axios';
7
7
  import { z } from 'zod';
8
8
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
9
9
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
+ import { createHttpServer } from './http-server.js';
10
11
  const __dirname = dirname(fileURLToPath(import.meta.url));
11
12
  function pkgVersion() {
12
13
  try {
@@ -99,12 +100,14 @@ async function put(path, body) {
99
100
  return fail(e);
100
101
  }
101
102
  }
102
- const server = new McpServer({ name: 'teamlink-mcp', version: pkgVersion() });
103
+ const registrations = [];
103
104
  function strictTool(name, description, inputSchema, callback) {
104
- return server.registerTool(name, {
105
- description,
106
- inputSchema: z.object(inputSchema).strict(),
107
- }, callback);
105
+ registrations.push((server) => {
106
+ server.registerTool(name, {
107
+ description,
108
+ inputSchema: z.object(inputSchema).strict(),
109
+ }, callback);
110
+ });
108
111
  }
109
112
  const allowedQueryParams = {
110
113
  '/accounts/search': new Set([
@@ -117,7 +120,7 @@ const allowedQueryParams = {
117
120
  'mode', 'q', 'cscId', 'contactId', 'firstName', 'lastName', 'fullName', 'shortName',
118
121
  'csaId', 'accountId', 'email', 'mobile', 'businessPhone', 'isActive', 'role', 'page', 'pageSize',
119
122
  ]),
120
- '/tasks/time-entries/search': new Set(['taskId', 'accountId', 'personId', 'type', 'q', 'dateFrom', 'dateTo', 'page', 'pageSize']),
123
+ '/tasks/time-entries/search': new Set(['taskId', 'accountId', 'personId', 'type', 'q', 'dateFrom', 'dateTo', 'page', 'pageSize', 'includeCrm']),
121
124
  '/tasks/search': new Set(['q', 'accountId', 'loggedForUserId', 'assignedToUserId', 'enteredByUserId', 'callType', 'priority', 'status', 'dateFrom', 'dateTo', 'page', 'pageSize']),
122
125
  '/crm/activities/search': new Set(['q', 'accountId', 'assignedToUserId', 'targetContactId', 'enteredByUserId', 'completed', 'dateDueFrom', 'dateDueTo', 'page', 'pageSize']),
123
126
  '/crm/activities/time-entries/search': new Set(['activityId', 'accountId', 'personId', 'q', 'dateFrom', 'dateTo', 'page', 'pageSize']),
@@ -191,14 +194,23 @@ strictTool('crm_search_contacts', 'Search contacts. `cscId` is canonical for CSC
191
194
  role: z.string().optional().describe(roleDescription),
192
195
  page: z.number().optional(), pageSize: z.number().optional(),
193
196
  }, async (args) => get('/contacts/search', args));
194
- strictTool('crm_get_contact', 'Get one contact by id. Response includes `role` (CSCClass) and `typeFlags` (contact type, distinct from role), `homeAccountId` (the CSAID this contact belongs to), and `isActive` — sourced from the CSPivotContactAccount pivot (CSPCA_Active), NOT the legacy/unused CSCActive column. An inactive contact may still be returned for historical/reporting purposes.', { contactId: z.number() }, async ({ contactId }) => get(`/contacts/${contactId}`));
197
+ strictTool('crm_get_contact', 'Get one contact by id. Response includes `role` (CSCClass) and `typeFlags` (contact type, distinct from role), `homeAccountId` (the CSAID this contact belongs to), and `isActive` — sourced from the CSPivotContactAccount pivot (CSPCA_Active), NOT the legacy/unused CSCActive column. An inactive contact may still be returned for historical/reporting purposes. If the calling key is Admin-scoped, the response also includes `password` (CSCPassword, the legacy plaintext web-app password) — omitted entirely for every other role; not returned by crm_search_contacts.', { contactId: z.number() }, async ({ contactId }) => get(`/contacts/${contactId}`));
195
198
  if (READWRITE) {
196
- strictTool('crm_create_contact', 'Create a contact under an account (also creates the active account link).', {
199
+ strictTool('crm_create_contact', 'Create a contact under an account (also creates the active account link). Role is gated by a staff ' +
200
+ 'hierarchy (A > M > E > {S,T,P} > C): the calling key\'s own role must outrank the role being assigned, ' +
201
+ 'or the call 403s (role_hierarchy_violation) — Admin keys are unrestricted, everyone else can only assign ' +
202
+ 'a role strictly below their own tier (no same-tier assignment either, e.g. an Engineer key cannot create ' +
203
+ 'another Engineer contact).', {
197
204
  accountId: z.number(), firstName: z.string(), lastName: z.string(), email: z.string(),
198
205
  mobile: z.string().optional(), businessPhone: z.string().optional(),
199
206
  role: z.string().optional().describe(roleDescription + ' Only settable for branch accounts; forced to C otherwise.'),
200
207
  }, async ({ accountId, ...body }) => post(`/accounts/${accountId}/contacts`, body));
201
- strictTool('crm_update_contact', 'Update a contact. Password only applied if supplied. `active` sets CSPivotContactAccount.CSPCA_Active for the account context (the legacy CSCActive column is never written).', {
208
+ strictTool('crm_update_contact', 'Update a contact. `active` sets CSPivotContactAccount.CSPCA_Active for the account context (the legacy ' +
209
+ 'CSCActive column is never written). Both the contact\'s CURRENT role and the role being set to are gated ' +
210
+ 'by the same staff hierarchy as crm_create_contact (A > M > E > {S,T,P} > C, Admin unrestricted) — the call ' +
211
+ '403s (role_hierarchy_violation) if the calling key cannot manage either one. Password is not settable via ' +
212
+ 'this tool (not exposed in this schema); the REST API additionally caps password writes to Admin-outranks-target ' +
213
+ 'and enforces 8-15 chars with upper/lower/digit.', {
202
214
  contactId: z.number(), firstName: z.string(), lastName: z.string(), email: z.string(), mobile: z.string().optional(),
203
215
  role: z.string().optional().describe(roleDescription),
204
216
  active: z.boolean().optional().describe('Sets CSPCA_Active (pivot) for the account context, not CSCActive.'),
@@ -237,19 +249,20 @@ strictTool('crm_activity_search_time_entries', 'Search CRM sales activity time e
237
249
  }, async (args) => get('/crm/activities/time-entries/search', args));
238
250
  // --- Tasks / time (read) ---
239
251
  strictTool('task_get', 'Get a task by id. Returns account/bill-to and contact actor fields as objects with IDs and names, while retaining raw ID fields.', { taskId: z.number() }, async ({ taskId }) => get(`/tasks/${taskId}`));
240
- strictTool('task_list_time_entries', 'List time/incidental entries + totals for a task. Can filter by staff person who performed the work (TMActivity.TMA_CSCID).', {
252
+ strictTool('task_list_time_entries', 'List time/incidental entries + totals for a task. Can filter by staff person who performed the work (TMActivity.TMA_CSCID). Response `totals` (and each row) split chargeable/OT hours into a normal figure plus a `chargeableHoursBranch`/`otHoursBranch` (and per-row `isBranch`) subtotal when the task\'s account is branch-flagged (CSAccount.CSABranch=\'Y\'): that work is productive but never billed, so it\'s reported separately from the billable total rather than folded into it.', {
241
253
  taskId: z.number().describe('Task ID (TMTask.TMTID / TMActivity.TMA_TMTID).'),
242
254
  personId: z.number().optional().describe('Filter by staff person who performed the work (TMActivity.TMA_CSCID).'),
243
255
  type: z.enum(['time', 'incidentals', 'all']).optional().describe('Entry kind based on TMActivity.TMACost: time = TMACost 0, incidentals = TMACost non-zero.'),
244
256
  }, async ({ taskId, personId, type }) => get(`/tasks/${taskId}/time-entries`, { personId, type }));
245
- strictTool('task_search_time_entries', 'Search task activity/time and incidentals across tasks. Supports filtering by account/customer (TMTask.TMT_CSAID), taskId, staff performer (TMActivity.TMA_CSCID), date range, entry kind, and text in public/internal descriptions. Date filters are `dateFrom`/`dateTo` only; do not use `fromDate`/`toDate`.', {
246
- taskId: z.number().optional().describe('Filter by task ID (TMActivity.TMA_TMTID).'),
247
- accountId: z.number().optional().describe('Filter by customer/account/company (CSAID). Maps through TMTask.TMT_CSAID for the task the entry belongs to.'),
257
+ strictTool('task_search_time_entries', 'Search task activity/time and incidentals across tasks. Supports filtering by account/customer (TMTask.TMT_CSAID), taskId, staff performer (TMActivity.TMA_CSCID), date range, entry kind, and text in public/internal descriptions. Date filters are `dateFrom`/`dateTo` only; do not use `fromDate`/`toDate`. Set `includeCrm=true` (ignored if `taskId` is given) to additionally union in CRM sales-activity time (TMAType=A) sorted into the same date-ordered result, matching what the mobile Time tab and Home screen show as one merged "my time" view — those CRM rows carry `sourceType: "crmActivity"` and an `activityId` instead of a `taskId`. Response `totals` (and each row) split chargeable/OT hours into a normal figure plus a `chargeableHoursBranch`/`otHoursBranch` (and per-row `isBranch`) subtotal: hours logged against a branch-flagged account (CSAccount.CSABranch=\'Y\') are productive but never billed, so it is reported separately rather than folded into the billable total. CRM rows never carry a branch flag (always fall into the non-branch bucket).', {
258
+ taskId: z.number().optional().describe('Filter by task ID (TMActivity.TMA_TMTID). When set, includeCrm is ignored (a task has no CRM equivalent).'),
259
+ accountId: z.number().optional().describe('Filter by customer/account/company (CSAID). Maps through TMTask.TMT_CSAID for the task the entry belongs to (or CRMActivity.CRMA_CSAID for CRM rows when includeCrm=true).'),
248
260
  personId: z.number().optional().describe('Filter by staff person who performed the work (TMActivity.TMA_CSCID).'),
249
261
  type: z.enum(['time', 'incidentals', 'all']).optional().describe('Entry kind based on TMActivity.TMACost: time = TMACost 0, incidentals = TMACost non-zero.'),
250
262
  q: z.string().optional().describe('Partial text match against TMActivity.TMADescription and TMActivity.TMAInternal.'),
251
263
  dateFrom: z.string().optional().describe('Activity date range start (TMActivity.TMADate), e.g. 2026-01-01. Use this exact parameter name, not fromDate.'),
252
264
  dateTo: z.string().optional().describe('Activity date range end (TMActivity.TMADate). Use this exact parameter name, not toDate.'),
265
+ includeCrm: z.boolean().optional().describe('Also include CRM sales-activity time entries (TMAType=A) in the results and totals, merged and sorted alongside task time. Ignored when taskId is set. Defaults to false (task time only).'),
253
266
  page: z.number().optional(),
254
267
  pageSize: z.number().optional(),
255
268
  }, async (args) => get('/tasks/time-entries/search', args));
@@ -299,14 +312,26 @@ strictTool('product_search', 'Search the read-only product catalog. `q` splits o
299
312
  inStock: z.boolean().optional().describe('true = PMPOnHand > 0; false = no stock on hand.'),
300
313
  page: z.number().optional(), pageSize: z.number().optional(),
301
314
  }, async (args) => get('/orders/products/search', args));
315
+ function createConfiguredServer() {
316
+ const server = new McpServer({ name: 'teamlink-mcp', version: pkgVersion() });
317
+ for (const register of registrations)
318
+ register(server);
319
+ return server;
320
+ }
302
321
  async function main() {
303
322
  if (!API_KEY) {
304
323
  console.error('[teamlink-mcp] WARNING: TEAMLINK_API_KEY is not set; all tool calls will fail until it is configured.');
305
324
  }
306
325
  console.error(`[teamlink-mcp] mode: ${READWRITE ? 'READ-WRITE (write tools enabled)' : 'read-only (set TEAMLINK_READWRITE=true to enable write tools)'}`);
307
- const transport = new StdioServerTransport();
308
- await server.connect(transport);
309
- console.error(`[teamlink-mcp] connected (stdio), proxying ${API_BASE}`);
326
+ if ((process.env.TEAMLINK_TRANSPORT ?? 'stdio') === 'http') {
327
+ const host = process.env.TEAMLINK_HTTP_HOST ?? '127.0.0.1';
328
+ const port = Number.parseInt(process.env.TEAMLINK_HTTP_PORT ?? '3000', 10);
329
+ createHttpServer(createConfiguredServer, { host, port, serverName: '@teamnetwork-nz/teamlink-mcp-server', bearerToken: process.env.TEAMLINK_HTTP_BEARER_TOKEN, allowedHosts: process.env.TEAMLINK_HTTP_ALLOWED_HOSTS?.split(',').map(v => v.trim()).filter(Boolean), allowedOrigins: process.env.TEAMLINK_HTTP_ALLOWED_ORIGINS?.split(',').map(v => v.trim()).filter(Boolean) }).listen(port, host, () => console.error(`[teamlink-mcp] connected (http ${host}:${port}/mcp), proxying ${API_BASE}`));
330
+ }
331
+ else {
332
+ await createConfiguredServer().connect(new StdioServerTransport());
333
+ console.error(`[teamlink-mcp] connected (stdio), proxying ${API_BASE}`);
334
+ }
310
335
  }
311
336
  main().catch((e) => {
312
337
  console.error('[teamlink-mcp] fatal', e);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/teamlink-mcp-server",
3
- "version": "0.5.8",
3
+ "version": "0.6.0",
4
4
  "private": false,
5
5
  "description": "stdio MCP server exposing tools that proxy the TEAMlink REST API",
6
6
  "main": "build/index.js",
@@ -13,6 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "build": "tsc",
16
+ "test": "npm run build && node --test tests/*.test.mjs",
16
17
  "start": "node build/index.js"
17
18
  },
18
19
  "dependencies": {