@giantswarm-io/pro 1.11.2 → 1.15.0-rc.2

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.
@@ -6,8 +6,8 @@
6
6
  */
7
7
 
8
8
  import { listFields } from '../fields.js';
9
- import { graphQLWithAuth } from '../api.js';
10
- import { resolveBoardId, DEFAULT_BOARD } from '../project.js';
9
+ import { graphQLWithAuth, withPartialData } from '../api.js';
10
+ import { resolveBoardId, BOARDS, DEFAULT_BOARD } from '../project.js';
11
11
  import { parseIssueRef } from '../rest-api.js';
12
12
  import { logger } from '../logger.js';
13
13
  import { READ_ONLY } from './annotations.js';
@@ -76,33 +76,72 @@ export async function handleGetBoardSchema(args, extra) {
76
76
  }
77
77
  }
78
78
 
79
- const ISSUE_PROJECT_ITEM_QUERY = `
80
- query IssueProjectItem($owner: String!, $repo: String!, $number: Int!) {
81
- repository(owner: $owner, name: $repo) {
82
- issue(number: $number) {
79
+ const ITEM_FIELD_VALUES = `
80
+ fieldValues(first: 30) {
81
+ nodes {
82
+ ... on ProjectV2ItemFieldSingleSelectValue {
83
+ name
84
+ field { ... on ProjectV2FieldCommon { name } }
85
+ }
86
+ ... on ProjectV2ItemFieldIterationValue {
83
87
  title
84
- url
85
- state
86
- projectItems(first: 20, includeArchived: false) {
88
+ field { ... on ProjectV2FieldCommon { name } }
89
+ }
90
+ ... on ProjectV2ItemFieldDateValue {
91
+ date
92
+ field { ... on ProjectV2FieldCommon { name } }
93
+ }
94
+ }
95
+ }
96
+ `;
97
+
98
+ /**
99
+ * The issue (or pull request) behind a URL, and its own project items.
100
+ *
101
+ * The issue's projectItems show a new item at once, but list only projects
102
+ * of the issue's owner. They are read first; ISSUE_BOARD_ITEM_QUERY finds an
103
+ * issue of another owner from the board side, through GitHub's search
104
+ * index, which lags a new item by minutes (pro#199).
105
+ */
106
+ const ISSUE_PROJECT_ITEMS_QUERY = `
107
+ query IssueProjectItems($resourceUrl: URI!) {
108
+ resource(url: $resourceUrl) {
109
+ __typename
110
+ ... on Issue {
111
+ id number title url state repository { nameWithOwner }
112
+ projectItems(first: 50, includeArchived: false) { nodes { id project { id } ${ITEM_FIELD_VALUES} } }
113
+ }
114
+ ... on PullRequest {
115
+ id number title url state repository { nameWithOwner }
116
+ projectItems(first: 50, includeArchived: false) { nodes { id project { id } ${ITEM_FIELD_VALUES} } }
117
+ }
118
+ }
119
+ }
120
+ `;
121
+
122
+ /**
123
+ * The issue behind a URL, and the board items of its repository whose text
124
+ * matches its number: the item whose content is the resolved node. The
125
+ * number narrows the board query; the node id decides.
126
+ */
127
+ const ISSUE_BOARD_ITEM_QUERY = `
128
+ query IssueBoardItem($resourceUrl: URI!, $boardId: ID!, $itemQuery: String!, $after: String) {
129
+ resource(url: $resourceUrl) {
130
+ __typename
131
+ ... on Issue { id number title url state repository { nameWithOwner } }
132
+ ... on PullRequest { id number title url state repository { nameWithOwner } }
133
+ }
134
+ board: node(id: $boardId) {
135
+ ... on ProjectV2 {
136
+ items(first: 100, after: $after, query: $itemQuery, archivedStates: [NOT_ARCHIVED]) {
137
+ pageInfo { hasNextPage endCursor }
87
138
  nodes {
88
139
  id
89
- project { id }
90
- fieldValues(first: 30) {
91
- nodes {
92
- ... on ProjectV2ItemFieldSingleSelectValue {
93
- name
94
- field { ... on ProjectV2FieldCommon { name } }
95
- }
96
- ... on ProjectV2ItemFieldIterationValue {
97
- title
98
- field { ... on ProjectV2FieldCommon { name } }
99
- }
100
- ... on ProjectV2ItemFieldDateValue {
101
- date
102
- field { ... on ProjectV2FieldCommon { name } }
103
- }
104
- }
140
+ content {
141
+ ... on Issue { id }
142
+ ... on PullRequest { id }
105
143
  }
144
+ ${ITEM_FIELD_VALUES}
106
145
  }
107
146
  }
108
147
  }
@@ -113,11 +152,11 @@ const ISSUE_PROJECT_ITEM_QUERY = `
113
152
  export const getItemByIssueTool = {
114
153
  name: 'get_item_by_issue',
115
154
  annotations: READ_ONLY,
116
- description: 'Find the project board item of one GitHub issue -- given as a URL, a short ref ("owner/repo#N") or owner/repo/issue_number -- without scanning the board. Returns the item id, title, url, state and field values, or item: null when the issue is not on the board.',
155
+ description: 'Find the project board item of one GitHub issue or pull request of any repository on the board -- given as a URL, a short ref ("owner/repo#N") or owner/repo/issue_number -- without scanning the board. Returns the item id, title, url, state and field values, or item: null with the reason when the issue is not on the board.',
117
156
  inputSchema: {
118
157
  type: 'object',
119
158
  properties: {
120
- issueUrl: { type: 'string', description: 'Issue URL or short ref (owner/repo#num)' },
159
+ issueUrl: { type: 'string', description: 'Issue or pull request URL, or short ref (owner/repo#num)' },
121
160
  owner: { type: 'string', description: 'Repository owner' },
122
161
  repo: { type: 'string', description: 'Repository name' },
123
162
  issue_number: { type: 'number', description: 'Issue number' },
@@ -130,59 +169,100 @@ export const getItemByIssueTool = {
130
169
  }
131
170
  };
132
171
 
172
+ const PULL_URL_RE = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/;
173
+
174
+ /** The issue's URL and its repository and number, from any accepted form. */
133
175
  function resolveIssueArgs(args) {
176
+ let ref;
134
177
  if (args.issueUrl) {
135
- return parseIssueRef(args.issueUrl);
136
- }
137
- if (args.owner && args.repo && args.issue_number) {
138
- return { owner: args.owner, repo: args.repo, issue_number: Number(args.issue_number) };
178
+ const pull = args.issueUrl.trim().match(PULL_URL_RE);
179
+ ref = pull
180
+ ? { owner: pull[1], repo: pull[2], issue_number: parseInt(pull[3], 10) }
181
+ : parseIssueRef(args.issueUrl);
182
+ } else if (args.owner && args.repo && args.issue_number) {
183
+ ref = { owner: args.owner, repo: args.repo, issue_number: Number(args.issue_number) };
184
+ } else {
185
+ throw new Error("Provide either 'issueUrl' (URL or owner/repo#num) or 'owner', 'repo', and 'issue_number'.");
139
186
  }
140
- throw new Error("Provide either 'issueUrl' (URL or owner/repo#num) or 'owner', 'repo', and 'issue_number'.");
187
+ return { ...ref, url: `https://github.com/${ref.owner}/${ref.repo}/issues/${ref.issue_number}` };
141
188
  }
142
189
 
143
- export async function handleGetItemByIssue(args, extra) {
144
- try {
145
- const token = extractToken(extra);
146
- const board = (args.board || DEFAULT_BOARD).toLowerCase();
147
- const boardId = resolveBoardId(board);
148
- const { owner, repo, issue_number } = resolveIssueArgs(args);
149
- logger.info('MCP: Looking up board item by issue', { board, owner, repo, issue_number });
190
+ /**
191
+ * Find the board item of one issue without scanning the board.
192
+ * @param {object} args - issueUrl, or owner, repo and issue_number
193
+ * @param {string} board - The board key (roadmap, customer)
194
+ * @param {string} [token] - Optional per-request GitHub token
195
+ * @returns {Promise<{item: object} | {item: null, reason: string}>}
196
+ */
197
+ export async function findBoardItemByIssue(args, board, token) {
198
+ const boardId = resolveBoardId(board);
199
+ const boardName = BOARDS[board].name;
200
+ const { owner, repo, issue_number, url } = resolveIssueArgs(args);
201
+ const ref = `${owner}/${repo}#${issue_number}`;
202
+ logger.info('MCP: Looking up board item by issue', { board, owner, repo, issue_number });
150
203
 
204
+ let issue;
205
+ let node;
206
+ // A project of the owner the grant cannot read answers FORBIDDEN for its
207
+ // item; the board side below still decides.
208
+ const { data } = await withPartialData(
209
+ graphQLWithAuth(ISSUE_PROJECT_ITEMS_QUERY, { resourceUrl: url }, token),
210
+ error => error.type === 'FORBIDDEN' || error.type === 'NOT_FOUND'
211
+ );
212
+ issue = data?.resource;
213
+ node = issue?.projectItems?.nodes?.find(item => item?.project?.id === boardId);
214
+
215
+ let after = null;
216
+ while (!node) {
151
217
  const result = await graphQLWithAuth(
152
- ISSUE_PROJECT_ITEM_QUERY,
153
- { owner, repo, number: issue_number },
218
+ ISSUE_BOARD_ITEM_QUERY,
219
+ { resourceUrl: url, boardId, itemQuery: `repo:${owner}/${repo} ${issue_number}`, after },
154
220
  token
155
221
  );
156
- const issue = result?.repository?.issue;
157
- const node = issue?.projectItems?.nodes?.find(item => item?.project?.id === boardId);
158
- if (!issue || !node) {
159
- return { content: [{ type: 'text', text: JSON.stringify({ item: null }) }] };
222
+ issue = result?.resource;
223
+ if (!issue) {
224
+ return { item: null, reason: `${ref} does not exist or is not readable with this GitHub grant.` };
225
+ }
226
+ if (!issue.id) {
227
+ return { item: null, reason: `${url} is a ${issue.__typename}, not an issue or pull request.` };
160
228
  }
229
+ const items = result?.board?.items;
230
+ node = items?.nodes?.find(item => item?.content?.id === issue.id);
231
+ after = items?.pageInfo?.hasNextPage ? items.pageInfo.endCursor : null;
232
+ if (!after) break;
233
+ }
161
234
 
162
- const fields = {};
163
- for (const fieldValue of node.fieldValues?.nodes || []) {
164
- const value = fieldValue?.name ?? fieldValue?.title ?? fieldValue?.date;
165
- if (fieldValue?.field?.name && value) {
166
- fields[fieldValue.field.name] = value;
167
- }
235
+ if (!node) {
236
+ return { item: null, reason: `${ref} is not on the ${boardName} (or its item is archived).` };
237
+ }
238
+
239
+ const fields = {};
240
+ for (const fieldValue of node.fieldValues?.nodes || []) {
241
+ const value = fieldValue?.name ?? fieldValue?.title ?? fieldValue?.date;
242
+ if (fieldValue?.field?.name && value) {
243
+ fields[fieldValue.field.name] = value;
168
244
  }
245
+ }
169
246
 
170
- return {
171
- content: [{
172
- type: 'text',
173
- text: JSON.stringify({
174
- item: {
175
- id: node.id,
176
- title: issue.title,
177
- number: issue_number,
178
- url: issue.url,
179
- repo: `${owner}/${repo}`,
180
- state: issue.state,
181
- fields
182
- }
183
- })
184
- }]
185
- };
247
+ return {
248
+ item: {
249
+ id: node.id,
250
+ title: issue.title,
251
+ number: issue.number,
252
+ url: issue.url,
253
+ repo: issue.repository.nameWithOwner,
254
+ state: issue.state,
255
+ fields
256
+ }
257
+ };
258
+ }
259
+
260
+ export async function handleGetItemByIssue(args, extra) {
261
+ try {
262
+ const token = extractToken(extra);
263
+ const board = (args.board || DEFAULT_BOARD).toLowerCase();
264
+ const found = await findBoardItemByIssue(args, board, token);
265
+ return { content: [{ type: 'text', text: JSON.stringify(found) }] };
186
266
  } catch (error) {
187
267
  logger.error('MCP: Error looking up board item by issue', { error: error.message });
188
268
  return { error: error.message };
@@ -141,11 +141,11 @@ export async function startHTTPServer(options = {}) {
141
141
  app.use('/.well-known/oauth-protected-resource', metadataHandler(protectedResourceMetadata));
142
142
 
143
143
  bearerAuthMiddleware = requireBearerAuth({
144
- verifier: createGitHubTokenVerifier(),
144
+ verifier: createGitHubTokenVerifier({ appSlug: process.env.GITHUB_APP_SLUG || undefined }),
145
145
  resourceMetadataUrl: new URL(metadataPath, publicUrl).href
146
146
  });
147
147
 
148
- logger.info('Bearer-only auth enabled — MCP clients present GitHub tokens obtained elsewhere; no authorization server is run');
148
+ logger.info(`Bearer-only auth enabled — MCP clients present GitHub tokens obtained elsewhere${process.env.GITHUB_APP_SLUG ? `, user access tokens of the GitHub App ${process.env.GITHUB_APP_SLUG} only` : ''}; no authorization server is run`);
149
149
  } else {
150
150
  logger.info('OAuth not configured — using GITHUB_API_TOKEN for all requests');
151
151
  }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * MCP Issue Relations Tools
3
+ *
4
+ * Exposes 3 tools for GitHub's issue relations besides parent/child
5
+ * (sub-issues.js): "blocked by" / "blocking" dependencies and "relates to"
6
+ * links, between issues of any repository:
7
+ * - list_issue_relations: List an issue's blocked-by, blocking and related issues
8
+ * - add_issue_relation: Set a relation between two issues
9
+ * - remove_issue_relation: Remove a relation between two issues
10
+ */
11
+
12
+ import { parseIssueRef } from '../rest-api.js';
13
+ import {
14
+ RELATION_TYPES,
15
+ listIssueRelations,
16
+ addIssueRelation,
17
+ removeIssueRelation
18
+ } from '../relations.js';
19
+ import { RELATIONS_PAGE } from '../project.js';
20
+ import { logger } from '../logger.js';
21
+ import { READ_ONLY, additiveWrite, destructiveWrite } from './annotations.js';
22
+
23
+ /**
24
+ * Extract the GitHub token from MCP request extra context.
25
+ * @param {Object} [extra] - MCP request extra context
26
+ * @returns {string|undefined}
27
+ */
28
+ function extractToken(extra) {
29
+ return extra?.authInfo?.token;
30
+ }
31
+
32
+ const RELATION_DESCRIPTION =
33
+ 'How issueUrl relates to relatedIssueUrl: "blocked_by" (relatedIssueUrl blocks issueUrl), ' +
34
+ '"blocking" (issueUrl blocks relatedIssueUrl) or "relates_to". Parent/child is not a relation here: use the sub-issue tools.';
35
+
36
+ const relationSchema = {
37
+ type: 'object',
38
+ properties: {
39
+ issueUrl: {
40
+ type: 'string',
41
+ description: 'Issue URL or short ref (owner/repo#num)'
42
+ },
43
+ relation: {
44
+ type: 'string',
45
+ enum: RELATION_TYPES,
46
+ description: RELATION_DESCRIPTION
47
+ },
48
+ relatedIssueUrl: {
49
+ type: 'string',
50
+ description: 'The other issue: URL or short ref (owner/repo#num), any repository'
51
+ }
52
+ },
53
+ required: ['issueUrl', 'relation', 'relatedIssueUrl']
54
+ };
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Tool: list_issue_relations
58
+ // ---------------------------------------------------------------------------
59
+
60
+ export const listIssueRelationsTool = {
61
+ name: 'list_issue_relations',
62
+ annotations: READ_ONLY,
63
+ description: `List the issues that block an issue (blockedBy), that it blocks (blocking) and that it relates to (relatesTo), with each one's state. Reads the first ${RELATIONS_PAGE} of each; \`hidden\` counts the related issues the caller cannot read, and a list holding more says \`truncated: true\` and its \`totalCount\`. Works for any issue, on a board or not. Parent/child links are read with list_sub_issues and get_parent_issue.`,
64
+ inputSchema: {
65
+ type: 'object',
66
+ properties: {
67
+ issueUrl: {
68
+ type: 'string',
69
+ description: 'Issue URL or short ref (owner/repo#num)'
70
+ }
71
+ },
72
+ required: ['issueUrl']
73
+ }
74
+ };
75
+
76
+ export async function handleListIssueRelations(args, extra) {
77
+ try {
78
+ const token = extractToken(extra);
79
+ const target = parseIssueRef(args.issueUrl);
80
+ logger.info('MCP: Listing issue relations', target);
81
+
82
+ const relations = await listIssueRelations(target, token);
83
+
84
+ return {
85
+ content: [{
86
+ type: 'text',
87
+ text: JSON.stringify(relations)
88
+ }]
89
+ };
90
+ } catch (error) {
91
+ logger.error('MCP: Error listing issue relations', { error: error.message });
92
+ return { error: error.message };
93
+ }
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // Tool: add_issue_relation
98
+ // ---------------------------------------------------------------------------
99
+
100
+ export const addIssueRelationTool = {
101
+ name: 'add_issue_relation',
102
+ annotations: additiveWrite(),
103
+ description: 'Set a relation between two issues of any repository: "blocked_by", "blocking" or "relates_to". Use it for a dependency between issues ("X cannot start before Y is done") instead of a "Blocked by" line in the issue body.',
104
+ inputSchema: relationSchema
105
+ };
106
+
107
+ export async function handleAddIssueRelation(args, extra) {
108
+ try {
109
+ const token = extractToken(extra);
110
+ const issue = parseIssueRef(args.issueUrl);
111
+ const related = parseIssueRef(args.relatedIssueUrl);
112
+ logger.info('MCP: Adding issue relation', { issue, relation: args.relation, related });
113
+
114
+ await addIssueRelation(issue, args.relation, related, token);
115
+
116
+ return {
117
+ content: [{
118
+ type: 'text',
119
+ text: JSON.stringify({ success: true, issue: args.issueUrl, relation: args.relation, related: args.relatedIssueUrl })
120
+ }]
121
+ };
122
+ } catch (error) {
123
+ logger.error('MCP: Error adding issue relation', { error: error.message });
124
+ return { error: error.message };
125
+ }
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Tool: remove_issue_relation
130
+ // ---------------------------------------------------------------------------
131
+
132
+ export const removeIssueRelationTool = {
133
+ name: 'remove_issue_relation',
134
+ annotations: destructiveWrite(),
135
+ description: 'Remove a "blocked_by", "blocking" or "relates_to" relation between two issues. "blocked_by" and "blocking" name one dependency from its two sides ("A blocked_by B" is "B blocking A"), so either removes it. Remove "relates_to" naming the issues as it was set.',
136
+ inputSchema: relationSchema
137
+ };
138
+
139
+ export async function handleRemoveIssueRelation(args, extra) {
140
+ try {
141
+ const token = extractToken(extra);
142
+ const issue = parseIssueRef(args.issueUrl);
143
+ const related = parseIssueRef(args.relatedIssueUrl);
144
+ logger.info('MCP: Removing issue relation', { issue, relation: args.relation, related });
145
+
146
+ await removeIssueRelation(issue, args.relation, related, token);
147
+
148
+ return {
149
+ content: [{
150
+ type: 'text',
151
+ text: JSON.stringify({ success: true, removed: true, issue: args.issueUrl, relation: args.relation, related: args.relatedIssueUrl })
152
+ }]
153
+ };
154
+ } catch (error) {
155
+ logger.error('MCP: Error removing issue relation', { error: error.message });
156
+ return { error: error.message };
157
+ }
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Exports
162
+ // ---------------------------------------------------------------------------
163
+
164
+ export const relationTools = [
165
+ listIssueRelationsTool,
166
+ addIssueRelationTool,
167
+ removeIssueRelationTool
168
+ ];
169
+
170
+ export const relationToolHandlers = {
171
+ list_issue_relations: handleListIssueRelations,
172
+ add_issue_relation: handleAddIssueRelation,
173
+ remove_issue_relation: handleRemoveIssueRelation
174
+ };
@@ -80,6 +80,7 @@ async function getSchemaResource(boardKey, token) {
80
80
  const hints = {};
81
81
  const dateFields = [];
82
82
  const textFields = [];
83
+ const numberFields = [];
83
84
  const iterationFields = {};
84
85
 
85
86
  for (const field of fields) {
@@ -102,8 +103,14 @@ async function getSchemaResource(boardKey, token) {
102
103
  dateFields.push(field.name);
103
104
  } else if (field.dataType === 'TEXT') {
104
105
  textFields.push(field.name);
106
+ } else if (field.dataType === 'NUMBER') {
107
+ numberFields.push(field.name);
105
108
  } else if (field.__typename === 'ProjectV2IterationField') {
106
- const iterations = field.configuration?.iterations || [];
109
+ // Current and upcoming first, then completed: filters take either.
110
+ const iterations = [
111
+ ...(field.configuration?.iterations || []),
112
+ ...(field.configuration?.completedIterations || [])
113
+ ];
107
114
  iterationFields[field.name] = iterations.map(iter => iter.title);
108
115
  }
109
116
  }
@@ -113,6 +120,7 @@ async function getSchemaResource(boardKey, token) {
113
120
  if (Object.keys(hints).length) schema.hints = hints;
114
121
  if (dateFields.length) schema.dateFields = dateFields;
115
122
  if (textFields.length) schema.textFields = textFields;
123
+ if (numberFields.length) schema.numberFields = numberFields;
116
124
  if (Object.keys(iterationFields).length) schema.iterationFields = iterationFields;
117
125
 
118
126
  // Document issue-level filters (not project fields, but available on list_issues)
@@ -122,10 +130,25 @@ async function getSchemaResource(boardKey, token) {
122
130
  label: 'Label name (e.g. "bug"). Comma-separated for OR matching.',
123
131
  state: '"open" or "closed"',
124
132
  keyword: 'Free text search on titles and text fields (word-prefix matching)',
133
+ milestone: 'Milestone title. Comma-separated for OR matching.',
134
+ type: 'Issue type (e.g. "Bug"). Comma-separated for OR matching.',
135
+ parentIssue: 'Parent issue URL or "owner/repo#number": its sub-issues.',
125
136
  updated: 'Last-updated date filter. Examples: ">@today-7d" (last 7 days), "<@today-30d" (older than 30 days), "@today" (today), ">2025-01-01" (after date)',
137
+ created: 'Creation date filter, same syntax as updated.',
138
+ closed: 'Closed date filter, same syntax as updated.',
126
139
  reason: '"completed", "not planned", or "reopened" (close reason for closed items)'
127
140
  };
128
141
 
142
+ // How the values of each field kind are written in filters and exclude
143
+ schema.filterSyntax = {
144
+ fields: 'Option names; comma-separated for OR.',
145
+ iterationFields: 'An iteration title (current, upcoming or completed) or "@current", "@next", "@previous".',
146
+ dateFields: 'Comparison or range: ">2026-01-01", "<@today-30d", "2026-01-01..2026-03-31", "@today".',
147
+ numberFields: 'Comparison or range: ">1", "1..3", "2".',
148
+ textFields: 'The exact text.',
149
+ exclude: 'Same keys and values as filters, plus the issueFilters names; matching items are left out.'
150
+ };
151
+
129
152
  // Compact repository info
130
153
  const repoInfo = REPOSITORY_SCHEMA[boardKey];
131
154
  if (repoInfo) {
@@ -28,6 +28,7 @@ import {
28
28
  } from '@modelcontextprotocol/sdk/types.js';
29
29
 
30
30
  import { tools, toolHandlers } from './tools.js';
31
+ import { validateToolArguments } from './validate.js';
31
32
  import { listResources, readResource } from './resources.js';
32
33
  import { logger } from '../logger.js';
33
34
  import { version } from '../version.js';
@@ -36,6 +37,8 @@ import { version } from '../version.js';
36
37
  * Create and configure the MCP server
37
38
  * @returns {Server} - Configured MCP server instance
38
39
  */
40
+ const toolsByName = new Map(tools.map(tool => [tool.name, tool]));
41
+
39
42
  export function createMCPServer() {
40
43
  const server = new Server(
41
44
  {
@@ -77,7 +80,14 @@ export function createMCPServer() {
77
80
  }
78
81
 
79
82
  try {
80
- const result = await handler(args || {}, extra);
83
+ // Every call is checked against the tool's declared inputSchema, so no
84
+ // handler runs with a missing, unknown or mistyped argument.
85
+ const validated = validateToolArguments(toolsByName.get(name), args);
86
+ if (validated.error) {
87
+ throw new Error(validated.error);
88
+ }
89
+
90
+ const result = await handler(validated.args, extra);
81
91
 
82
92
  // If result has an error, throw it
83
93
  if (result.error) {