@teamnetwork-nz/teamlink-mcp-server 0.5.7 → 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,38 +100,70 @@ 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 = [];
104
+ function strictTool(name, description, inputSchema, callback) {
105
+ registrations.push((server) => {
106
+ server.registerTool(name, {
107
+ description,
108
+ inputSchema: z.object(inputSchema).strict(),
109
+ }, callback);
110
+ });
111
+ }
103
112
  const allowedQueryParams = {
104
- '/accounts/search': new Set(['q', 'phone', 'exactWebsite', 'page', 'pageSize']),
113
+ '/accounts/search': new Set([
114
+ 'mode', 'q', 'csaId', 'accountId', 'alphaId', 'name', 'address', 'phone', 'website',
115
+ 'exactWebsite', 'isActive', 'isCustomer', 'isProspect', 'isSupplier', 'isBranch',
116
+ 'branchId', 'teamId', 'page', 'pageSize',
117
+ ]),
105
118
  '/accounts': new Set(['search', 'isActive', 'isCustomer', 'isProspect', 'isSupplier', 'isBranch', 'branchId', 'teamId', 'page', 'pageSize']),
106
- '/contacts/search': new Set(['q', 'accountId', 'email', 'mobile', 'businessPhone', 'isActive', 'role', 'page', 'pageSize']),
107
- '/tasks/time-entries/search': new Set(['taskId', 'accountId', 'personId', 'type', 'q', 'dateFrom', 'dateTo', 'page', 'pageSize']),
119
+ '/contacts/search': new Set([
120
+ 'mode', 'q', 'cscId', 'contactId', 'firstName', 'lastName', 'fullName', 'shortName',
121
+ 'csaId', 'accountId', 'email', 'mobile', 'businessPhone', 'isActive', 'role', 'page', 'pageSize',
122
+ ]),
123
+ '/tasks/time-entries/search': new Set(['taskId', 'accountId', 'personId', 'type', 'q', 'dateFrom', 'dateTo', 'page', 'pageSize', 'includeCrm']),
108
124
  '/tasks/search': new Set(['q', 'accountId', 'loggedForUserId', 'assignedToUserId', 'enteredByUserId', 'callType', 'priority', 'status', 'dateFrom', 'dateTo', 'page', 'pageSize']),
125
+ '/crm/activities/search': new Set(['q', 'accountId', 'assignedToUserId', 'targetContactId', 'enteredByUserId', 'completed', 'dateDueFrom', 'dateDueTo', 'page', 'pageSize']),
126
+ '/crm/activities/time-entries/search': new Set(['activityId', 'accountId', 'personId', 'q', 'dateFrom', 'dateTo', 'page', 'pageSize']),
109
127
  '/orders/search': new Set(['q', 'advanced', 'accountId', 'branchId', 'enteredByUserId', 'authorisedByUserId', 'vendorId', 'receivedByUserId', 'approvedByUserId', 'invoicedByUserId', 'returnAuthorisedByUserId', 'creditedByUserId', 'orderType', 'dateFrom', 'dateTo', 'received', 'invoiced', 'returned', 'page', 'pageSize']),
110
- '/orders/products/search': new Set(['q', 'vendorId', 'manufacturer', 'category', 'page', 'pageSize']),
128
+ '/orders/products/search': new Set(['q', 'supplierId', 'vendorId', 'manufacturer', 'category', 'inStock', 'page', 'pageSize']),
111
129
  };
112
130
  // --- Identity ---
113
- server.tool('teamlink_whoami', 'Return the authenticated TEAMlink user context for the configured API key, including `roleClass` (CSCClass) and `homeAccountId` (CSAID — the identity key scoping staff vs customer visibility).', {}, async () => get('/me'));
131
+ strictTool('teamlink_whoami', 'Return the authenticated TEAMlink user context for the configured API key, including `roleClass` (CSCClass) and `homeAccountId` (CSAID — the identity key scoping staff vs customer visibility).', {}, async () => get('/me'));
114
132
  // --- CRM: accounts ---
115
- server.tool('crm_search_accounts', 'Search customer accounts by account id, name, alpha id, email domain, website, or normalized phone. Also accepts explicit phone and exactWebsite duplicate-detection style inputs. Results include selector objects for industry/source/salesStatus and named team/contact reference objects where available.', {
116
- q: z.string().describe('Search text: account ID (CSAID), account name, alpha ID, email domain, website, or phone digits.'),
117
- phone: z.string().optional().describe('Optional phone search; punctuation/spaces are ignored and partial digit matches are allowed against CSAccount.CSAPhone.'),
118
- exactWebsite: z.string().optional().describe('Optional exact website match against CSAccount.CSAWebsite.'),
133
+ strictTool('crm_search_accounts', 'Search customer accounts. `csaId` is canonical for CSAccount.CSAID; `accountId` is accepted as a compatibility alias. Default mode is standard: exact case-insensitive matches. Fuzzy mode performs partial text/phone matching and name DIFFERENCE() matching. `isActive` defaults true unless explicitly set.', {
134
+ mode: z.enum(['standard', 'fuzzy']).optional().describe('Search mode. standard=exact case-insensitive matching; fuzzy=partial matching plus DIFFERENCE() for names. Defaults to standard.'),
135
+ q: z.string().optional().describe('General search value matched against csaId, alphaId, name, address, phone, and website.'),
136
+ csaId: z.number().optional().describe('Canonical account primary key (CSAccount.CSAID).'),
137
+ accountId: z.number().optional().describe('Compatibility alias for csaId. Prefer csaId.'),
138
+ alphaId: z.string().optional(),
139
+ name: z.string().optional(),
140
+ address: z.string().optional(),
141
+ phone: z.string().optional().describe('Phone search; punctuation/spaces are ignored.'),
142
+ website: z.string().optional(),
143
+ exactWebsite: z.string().optional().describe('Compatibility alias for website. Prefer website.'),
144
+ isActive: z.boolean().optional().describe('Defaults to true if omitted.'),
145
+ isCustomer: z.boolean().optional(),
146
+ isProspect: z.boolean().optional(),
147
+ isSupplier: z.boolean().optional(),
148
+ isBranch: z.boolean().optional(),
149
+ branchId: z.string().optional(),
150
+ teamId: z.number().optional(),
119
151
  page: z.number().optional(),
120
152
  pageSize: z.number().optional(),
121
153
  }, async (args) => get('/accounts/search', args));
122
- server.tool('crm_list_accounts', 'List/filter accounts. `isActive` filters on CSAActive — only active accounts are eligible for transactional activity (orders/tasks). Results include selector objects for industry/source/salesStatus and named team/contact reference objects where available.', {
154
+ strictTool('crm_list_accounts', 'Deprecated compatibility wrapper for listing/filtering accounts. Prefer crm_search_accounts for new work. `isActive` filters on CSAActive — only active accounts are eligible for transactional activity (orders/tasks).', {
123
155
  search: z.string().optional(), isActive: z.boolean().optional(), isCustomer: z.boolean().optional(), isProspect: z.boolean().optional(),
124
- isSupplier: z.boolean().optional(), branchId: z.string().optional(), page: z.number().optional(), pageSize: z.number().optional(),
156
+ isSupplier: z.boolean().optional(), isBranch: z.boolean().optional(), branchId: z.string().optional(), teamId: z.number().optional(),
157
+ page: z.number().optional(), pageSize: z.number().optional(),
125
158
  }, async (args) => get('/accounts', args));
126
159
  // `accountId` (CSAID) is the absolute source-of-truth identity key for this account
127
160
  // and everything linked to it (contacts, orders, tasks, ...) — see lookup_selectors
128
161
  // and crm_search_accounts for how to resolve one. Response `isActive` = CSAActive:
129
162
  // only active accounts are eligible for transactional activity (orders/tasks).
130
- server.tool('crm_get_account', 'Get one account by id (CSAID). Response `isActive` (CSAActive) gates transactional eligibility for orders/tasks. Lookup-backed fields include industry/source/salesStatus {code,label}, team {teamId,name}, and accountManager/preferredEngineer/backupEngineer/bizDevManager {userId,name}.', { accountId: z.number() }, async ({ accountId }) => get(`/accounts/${accountId}`));
131
- server.tool('crm_list_account_contacts', 'List contacts linked to an account. Defaults to active-only (CSPCA_Active); pass includeInactive=true to also return deactivated contacts for historical/reporting purposes — inactive does not mean deleted.', { accountId: z.number(), includeInactive: z.boolean().optional() }, async ({ accountId, includeInactive }) => get(`/accounts/${accountId}/contacts`, { includeInactive }));
163
+ strictTool('crm_get_account', 'Get one account by id (CSAID). Response `isActive` (CSAActive) gates transactional eligibility for orders/tasks. Lookup-backed fields include industry/source/salesStatus {code,label}, team {teamId,name}, and accountManager/preferredEngineer/backupEngineer/bizDevManager {userId,name}.', { accountId: z.number() }, async ({ accountId }) => get(`/accounts/${accountId}`));
164
+ strictTool('crm_list_account_contacts', 'List contacts linked to an account. Defaults to active-only (CSPCA_Active); pass includeInactive=true to also return deactivated contacts for historical/reporting purposes — inactive does not mean deleted.', { accountId: z.number(), includeInactive: z.boolean().optional() }, async ({ accountId, includeInactive }) => get(`/accounts/${accountId}/contacts`, { includeInactive }));
132
165
  if (READWRITE) {
133
- server.tool('crm_create_account', 'Create an account. Returns duplicate-candidate warnings unless createAnyway=true.', {
166
+ strictTool('crm_create_account', 'Create an account. Returns duplicate-candidate warnings unless createAnyway=true.', {
134
167
  name: z.string(), alphaId: z.string().optional(), website: z.string().optional(), phone: z.string().optional(),
135
168
  isCustomer: z.boolean().optional(), isProspect: z.boolean().optional(), createAnyway: z.boolean().optional(),
136
169
  }, async (args) => post('/accounts', args));
@@ -143,49 +176,97 @@ if (READWRITE) {
143
176
  // TYPE) — typeFlags.isAdminContact means a client-side admin/accounts contact,
144
177
  // NOT the application admin role (role="A").
145
178
  const roleDescription = 'CSCClass web-app role: A=Administrator, C=Customer, E=Engineer, M=Business Manager, P=Partner, S=Sales, T=Account Manager.';
146
- server.tool('crm_search_contacts', 'Search contacts by contact id, names, email, mobile, business phone, account id, web-app role (CSCClass), and active pivot status.', {
147
- q: z.string().optional(), accountId: z.number().optional(), email: z.string().optional(),
148
- mobile: z.string().optional().describe('Filter by mobile phone (CSContact.CSCMobile); punctuation/spaces are ignored and partial digit matches are allowed.'),
149
- businessPhone: z.string().optional().describe('Filter by business/DDI phone (CSContact.CSCBizPhone); punctuation/spaces are ignored and partial digit matches are allowed.'),
179
+ strictTool('crm_search_contacts', 'Search contacts. `cscId` is canonical for CSContact.CSCID; `contactId` is accepted as a compatibility alias. `csaId` is canonical for account linkage; `accountId` is accepted as a compatibility alias. Default mode is standard: exact case-insensitive matches. Fuzzy mode performs partial matching.', {
180
+ mode: z.enum(['standard', 'fuzzy']).optional().describe('Search mode. standard=exact case-insensitive matching; fuzzy=partial matching. Defaults to standard.'),
181
+ q: z.string().optional().describe('General search value matched against cscId/contactId, names, email, mobile, and business phone.'),
182
+ cscId: z.number().optional().describe('Canonical contact primary key (CSContact.CSCID).'),
183
+ contactId: z.number().optional().describe('Compatibility alias for cscId. Prefer cscId.'),
184
+ firstName: z.string().optional(),
185
+ lastName: z.string().optional(),
186
+ fullName: z.string().optional(),
187
+ shortName: z.string().optional(),
188
+ csaId: z.number().optional().describe('Canonical linked account primary key (CSAccount.CSAID / CSPivotContactAccount.CSPCA_CSAID).'),
189
+ accountId: z.number().optional().describe('Compatibility alias for csaId. Prefer csaId.'),
190
+ email: z.string().optional(),
191
+ mobile: z.string().optional().describe('Mobile phone search; punctuation/spaces are ignored.'),
192
+ businessPhone: z.string().optional().describe('Business/DDI phone search; punctuation/spaces are ignored.'),
150
193
  isActive: z.boolean().optional().describe('Filter by CSPivotContactAccount.CSPCA_Active when pivot context is joined.'),
151
194
  role: z.string().optional().describe(roleDescription),
152
195
  page: z.number().optional(), pageSize: z.number().optional(),
153
196
  }, async (args) => get('/contacts/search', args));
154
- server.tool('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}`));
155
198
  if (READWRITE) {
156
- server.tool('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).', {
157
204
  accountId: z.number(), firstName: z.string(), lastName: z.string(), email: z.string(),
158
205
  mobile: z.string().optional(), businessPhone: z.string().optional(),
159
206
  role: z.string().optional().describe(roleDescription + ' Only settable for branch accounts; forced to C otherwise.'),
160
207
  }, async ({ accountId, ...body }) => post(`/accounts/${accountId}/contacts`, body));
161
- server.tool('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.', {
162
214
  contactId: z.number(), firstName: z.string(), lastName: z.string(), email: z.string(), mobile: z.string().optional(),
163
215
  role: z.string().optional().describe(roleDescription),
164
216
  active: z.boolean().optional().describe('Sets CSPCA_Active (pivot) for the account context, not CSCActive.'),
165
217
  }, async ({ contactId, ...body }) => put(`/contacts/${contactId}`, body));
166
218
  }
167
219
  // --- Lookups ---
168
- server.tool('lookup_selectors', 'Get options for a CSSelectors list (Industry, Source, SalesStatus, OrderType, IncomeCat, City, Country, ...).', { selectorClass: z.string() }, async ({ selectorClass }) => get(`/lookups/selectors/${encodeURIComponent(selectorClass)}`));
169
- server.tool('lookup_branches', 'List branches.', {}, async () => get('/lookups/branches'));
220
+ strictTool('lookup_selectors', 'Get options for a CSSelectors list (Industry, Source, SalesStatus, OrderType, IncomeCat, City, Country, ...).', { selectorClass: z.string() }, async ({ selectorClass }) => get(`/lookups/selectors/${encodeURIComponent(selectorClass)}`));
221
+ strictTool('lookup_branches', 'List branches.', {}, async () => get('/lookups/branches'));
222
+ // --- CRM: sales activities / time (read) ---
223
+ strictTool('crm_activity_get', 'Get one CRM sales activity by id (CRMActivity.CRMAID). Returns account, enteredBy, assignedTo, targetContact, type/subType selector labels, due/completed dates, and completed boolean.', { activityId: z.number().describe('CRM activity ID (CRMActivity.CRMAID).') }, async ({ activityId }) => get(`/crm/activities/${activityId}`));
224
+ strictTool('crm_activity_search', 'Search/filter CRM sales activities (CRMActivity). Supports customer/account, assigned-to staff, targeted-at contact, entered-by staff, completed/open state, due-date range, and free text. `completed=true` means CRMADateCompleted is not null; `completed=false` means open.', {
225
+ q: z.string().optional().describe('Free text: exact activity ID match, or partial match on description/type/subtype labels.'),
226
+ accountId: z.number().optional().describe('Filter by customer/account/company (CSAID). Maps to CRMActivity.CRMA_CSAID.'),
227
+ assignedToUserId: z.number().optional().describe('Filter by assigned staff/contact (CRMActivity.CRMAAssignedTo_CSCID).'),
228
+ targetContactId: z.number().optional().describe('Filter by targeted-at contact (CRMActivity.CRMA_CSCID_Target).'),
229
+ enteredByUserId: z.number().optional().describe('Filter by staff/contact who entered the activity (CRMActivity.CRMA_CSCID).'),
230
+ completed: z.boolean().optional().describe('true = CRMADateCompleted is not null; false = CRMADateCompleted is null; omitted = all.'),
231
+ dateDueFrom: z.string().optional().describe('Due-date range start (CRMActivity.CRMADateDue), e.g. 2026-01-01.'),
232
+ dateDueTo: z.string().optional().describe('Due-date range end (CRMActivity.CRMADateDue).'),
233
+ page: z.number().optional(),
234
+ pageSize: z.number().optional(),
235
+ }, async (args) => get('/crm/activities/search', args));
236
+ strictTool('crm_activity_list_time_entries', 'List time entries + totals for a CRM sales activity. CRM activity time is TMActivity with TMAType=A and TMA_CRMAID=CRMActivity.CRMAID.', {
237
+ activityId: z.number().describe('CRM activity ID (CRMActivity.CRMAID / TMActivity.TMA_CRMAID).'),
238
+ personId: z.number().optional().describe('Filter by staff person who performed the work (TMActivity.TMA_CSCID).'),
239
+ }, async ({ activityId, personId }) => get(`/crm/activities/${activityId}/time-entries`, { personId }));
240
+ strictTool('crm_activity_search_time_entries', 'Search CRM sales activity time entries across activities. Supports filtering by activityId, account/customer (CRMActivity.CRMA_CSAID), staff performer (TMActivity.TMA_CSCID), date range, and text in time-entry or activity descriptions.', {
241
+ activityId: z.number().optional().describe('Filter by CRM activity ID (TMActivity.TMA_CRMAID).'),
242
+ accountId: z.number().optional().describe('Filter by customer/account/company (CSAID). Maps through CRMActivity.CRMA_CSAID.'),
243
+ personId: z.number().optional().describe('Filter by staff person who performed the work (TMActivity.TMA_CSCID).'),
244
+ q: z.string().optional().describe('Partial text match against TMActivity.TMADescription, TMActivity.TMAInternal, or CRMActivity.CRMADescription.'),
245
+ dateFrom: z.string().optional().describe('Activity time-entry date range start (TMActivity.TMADate), e.g. 2026-01-01.'),
246
+ dateTo: z.string().optional().describe('Activity time-entry date range end (TMActivity.TMADate).'),
247
+ page: z.number().optional(),
248
+ pageSize: z.number().optional(),
249
+ }, async (args) => get('/crm/activities/time-entries/search', args));
170
250
  // --- Tasks / time (read) ---
171
- server.tool('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}`));
172
- server.tool('task_list_time_entries', 'List time/incidental entries + totals for a task. Can filter by staff person who performed the work (TMActivity.TMA_CSCID).', {
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}`));
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.', {
173
253
  taskId: z.number().describe('Task ID (TMTask.TMTID / TMActivity.TMA_TMTID).'),
174
254
  personId: z.number().optional().describe('Filter by staff person who performed the work (TMActivity.TMA_CSCID).'),
175
255
  type: z.enum(['time', 'incidentals', 'all']).optional().describe('Entry kind based on TMActivity.TMACost: time = TMACost 0, incidentals = TMACost non-zero.'),
176
256
  }, async ({ taskId, personId, type }) => get(`/tasks/${taskId}/time-entries`, { personId, type }));
177
- server.tool('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`.', {
178
- taskId: z.number().optional().describe('Filter by task ID (TMActivity.TMA_TMTID).'),
179
- 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).'),
180
260
  personId: z.number().optional().describe('Filter by staff person who performed the work (TMActivity.TMA_CSCID).'),
181
261
  type: z.enum(['time', 'incidentals', 'all']).optional().describe('Entry kind based on TMActivity.TMACost: time = TMACost 0, incidentals = TMACost non-zero.'),
182
262
  q: z.string().optional().describe('Partial text match against TMActivity.TMADescription and TMActivity.TMAInternal.'),
183
263
  dateFrom: z.string().optional().describe('Activity date range start (TMActivity.TMADate), e.g. 2026-01-01. Use this exact parameter name, not fromDate.'),
184
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).'),
185
266
  page: z.number().optional(),
186
267
  pageSize: z.number().optional(),
187
268
  }, async (args) => get('/tasks/time-entries/search', args));
188
- server.tool('task_search', 'Search/filter tasks. Supports filtering by customer/account, logged-for contact, assigned staff member, entered-by staff member, call type, priority/severity, open/closed status, a date-logged range, and/or free text. Defaults to open tasks only unless status is set. Every filter is optional and combinable. Results include account/loggedFor/assignedTo/enteredBy objects with names, plus raw IDs.', {
269
+ strictTool('task_search', 'Search/filter tasks. Supports filtering by customer/account, logged-for contact, assigned staff member, entered-by staff member, call type, priority/severity, open/closed status, a date-logged range, and/or free text. Defaults to open tasks only unless status is set. Every filter is optional and combinable. Results include account/loggedFor/assignedTo/enteredBy objects with names, plus raw IDs.', {
189
270
  q: z.string().optional().describe('Free text: exact task ID match, or partial match on task name/description.'),
190
271
  accountId: z.number().optional().describe('Filter by customer/account/company (CSAID). Maps to TMTask.TMT_CSAID — the account the task was logged for.'),
191
272
  loggedForUserId: z.number().optional().describe('Filter by the customer contact who requested/is authorising the task (TMTask.TMTLoggedBy_CSCID).'),
@@ -199,9 +280,9 @@ server.tool('task_search', 'Search/filter tasks. Supports filtering by customer/
199
280
  page: z.number().optional(), pageSize: z.number().optional(),
200
281
  }, async (args) => get('/tasks/search', args));
201
282
  // --- Orders / PM (read) ---
202
- server.tool('order_get', 'Get an order header + totals. Returns account/bill-to and contact actor fields as objects with IDs and names, while retaining raw ID fields. `orderType` is returned as { code, label } from CSSelectors/OrderType.', { orderId: z.number() }, async ({ orderId }) => get(`/orders/${orderId}`));
203
- server.tool('order_list_items', 'List order line items.', { orderId: z.number() }, async ({ orderId }) => get(`/orders/${orderId}/items`));
204
- server.tool('order_search', 'Search/filter orders. Supports filtering by customer/account, branch, order type, a date-raised range, who entered or authorised the order, who received/approved/invoiced/returned/credited a line, received/invoiced/returned status, and/or free text (order id, invoice/credit/RA reference, or with advanced=true also notes and product codes/descriptions). Every filter is optional and combinable. Results include account/enteredBy/authorisedBy objects with names, plus raw IDs. Returned `orderType` is { code, label } resolved from CSSelectors/OrderType.', {
283
+ strictTool('order_get', 'Get an order header + totals. Returns account/bill-to and contact actor fields as objects with IDs and names, while retaining raw ID fields. `orderType` is returned as { code, label } from CSSelectors/OrderType.', { orderId: z.number() }, async ({ orderId }) => get(`/orders/${orderId}`));
284
+ strictTool('order_list_items', 'List order line items.', { orderId: z.number() }, async ({ orderId }) => get(`/orders/${orderId}/items`));
285
+ strictTool('order_search', 'Search/filter orders. Supports filtering by customer/account, branch, order type, a date-raised range, who entered or authorised the order, who received/approved/invoiced/returned/credited a line, received/invoiced/returned status, and/or free text (order id, invoice/credit/RA reference, or with advanced=true also notes and product codes/descriptions). Every filter is optional and combinable. Results include account/enteredBy/authorisedBy objects with names, plus raw IDs. Returned `orderType` is { code, label } resolved from CSSelectors/OrderType.', {
205
286
  q: z.string().optional().describe('Free text search — order id (exact), invoice/credit/RA reference (partial); with advanced=true also order notes and line product code/OEM code/descriptions.'),
206
287
  advanced: z.boolean().optional().describe('Widen `q` to also match order notes and line product code/OEM code/descriptions.'),
207
288
  accountId: z.number().optional().describe('Filter by customer/account/company (CSAID). Maps to PMOrder.PMO_CSAID.'),
@@ -222,20 +303,35 @@ server.tool('order_search', 'Search/filter orders. Supports filtering by custome
222
303
  returned: z.enum(['yes', 'no']).optional().describe('Whether at least one line has a return reason set. Same "at least one line" semantics as `received`.'),
223
304
  page: z.number().optional(), pageSize: z.number().optional(),
224
305
  }, async (args) => get('/orders/search', args));
225
- server.tool('product_search', 'Search the (read-only) product catalog. `q` splits on whitespace and requires every word to match description/code/OEM code.', {
226
- q: z.string().optional(), vendorId: z.number().optional(),
306
+ strictTool('product_search', 'Search the read-only product catalog. `q` splits on whitespace and requires every word to match as a substring in code, OEM code, description, manufacturer, or category. Filter by supplier/vendor and stock availability.', {
307
+ q: z.string().optional(),
308
+ supplierId: z.number().optional().describe('Canonical supplier/vendor account id (PMProduct.PMPVendor_CSAID).'),
309
+ vendorId: z.number().optional().describe('Compatibility alias for supplierId. Prefer supplierId.'),
227
310
  manufacturer: z.string().optional().describe('Exact match on PMPManufacturer.'),
228
311
  category: z.string().optional().describe('Exact match on PMPProductCategory_ID.'),
312
+ inStock: z.boolean().optional().describe('true = PMPOnHand > 0; false = no stock on hand.'),
229
313
  page: z.number().optional(), pageSize: z.number().optional(),
230
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
+ }
231
321
  async function main() {
232
322
  if (!API_KEY) {
233
323
  console.error('[teamlink-mcp] WARNING: TEAMLINK_API_KEY is not set; all tool calls will fail until it is configured.');
234
324
  }
235
325
  console.error(`[teamlink-mcp] mode: ${READWRITE ? 'READ-WRITE (write tools enabled)' : 'read-only (set TEAMLINK_READWRITE=true to enable write tools)'}`);
236
- const transport = new StdioServerTransport();
237
- await server.connect(transport);
238
- 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
+ }
239
335
  }
240
336
  main().catch((e) => {
241
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.7",
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": {