@grec0/mcp-mantis 0.3.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.
- package/LICENSE +21 -0
- package/README.md +133 -0
- package/dist/config.js +95 -0
- package/dist/constants.js +93 -0
- package/dist/date-filter.js +58 -0
- package/dist/index.js +30 -0
- package/dist/mantis.js +296 -0
- package/dist/mcp.js +12 -0
- package/dist/search/embedder.js +58 -0
- package/dist/search/highlight.js +48 -0
- package/dist/search/store.js +117 -0
- package/dist/search/sync.js +92 -0
- package/dist/search/tools.js +170 -0
- package/dist/server.js +31 -0
- package/dist/tools/issues.js +448 -0
- package/dist/tools/meta.js +51 -0
- package/dist/tools/notes.js +29 -0
- package/dist/tools/relationships.js +49 -0
- package/dist/tools/shared.js +72 -0
- package/package.json +79 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { dateFilterSchema, hasDateFilter, matchesDateFilter, } from '../date-filter.js';
|
|
3
|
+
import { handler, jsonResult, runWithConcurrency } from '../tools/shared.js';
|
|
4
|
+
import { extractSnippet, extractTerms, hasTermMatch, highlightText } from './highlight.js';
|
|
5
|
+
import { SearchSyncService } from './sync.js';
|
|
6
|
+
const coerceBool = (val) => (val === 'true' ? true : val === 'false' ? false : val);
|
|
7
|
+
function buildHighlights(summary, description, terms) {
|
|
8
|
+
const h = {};
|
|
9
|
+
if (summary) {
|
|
10
|
+
const highlighted = highlightText(summary, terms);
|
|
11
|
+
if (highlighted !== summary)
|
|
12
|
+
h.summary = highlighted;
|
|
13
|
+
}
|
|
14
|
+
if (description && hasTermMatch(description, terms)) {
|
|
15
|
+
h.description = extractSnippet(description, terms);
|
|
16
|
+
}
|
|
17
|
+
return Object.keys(h).length > 0 ? h : null;
|
|
18
|
+
}
|
|
19
|
+
export function registerSearchTools(server, client, store, embedder) {
|
|
20
|
+
server.registerTool('mantis_search_issues', {
|
|
21
|
+
title: 'Semantic issue search',
|
|
22
|
+
description: 'Search issues by natural-language meaning (not keywords), useful to find similar/duplicate incidents. ' +
|
|
23
|
+
'The index must be built first with mantis_rebuild_search_index. Without "select" only id+score are returned.',
|
|
24
|
+
inputSchema: {
|
|
25
|
+
query: z.string().min(1).describe('Natural-language query.'),
|
|
26
|
+
top_n: z
|
|
27
|
+
.number()
|
|
28
|
+
.int()
|
|
29
|
+
.positive()
|
|
30
|
+
.max(50)
|
|
31
|
+
.optional()
|
|
32
|
+
.describe('Results to return (default 10, max 50).'),
|
|
33
|
+
select: z
|
|
34
|
+
.string()
|
|
35
|
+
.optional()
|
|
36
|
+
.describe('Comma-separated fields to fetch per result, e.g. "id,summary,status,handler".'),
|
|
37
|
+
highlight: z
|
|
38
|
+
.preprocess(coerceBool, z.boolean().optional())
|
|
39
|
+
.describe('If true, add a "highlights" field with query terms bolded.'),
|
|
40
|
+
...dateFilterSchema,
|
|
41
|
+
},
|
|
42
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
|
|
43
|
+
}, handler(async ({ query, top_n, select, highlight, updated_after, updated_before, created_after, created_before, }) => {
|
|
44
|
+
if ((await store.count()) === 0) {
|
|
45
|
+
return {
|
|
46
|
+
content: [
|
|
47
|
+
{
|
|
48
|
+
type: 'text',
|
|
49
|
+
text: 'Search index is empty. Run mantis_rebuild_search_index first.',
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
|
+
isError: true,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const topN = top_n ?? 10;
|
|
56
|
+
const dateFilter = {
|
|
57
|
+
updated_after,
|
|
58
|
+
updated_before,
|
|
59
|
+
created_after,
|
|
60
|
+
created_before,
|
|
61
|
+
};
|
|
62
|
+
const filterActive = hasDateFilter(dateFilter);
|
|
63
|
+
const terms = highlight ? extractTerms(query) : [];
|
|
64
|
+
const queryVector = await embedder.embed(query);
|
|
65
|
+
// When a date filter is active we cannot know upfront how many top-scored
|
|
66
|
+
// candidates survive it, so rank the whole index and date-filter using the
|
|
67
|
+
// (cheap, in-memory) store metadata, stopping once topN survivors are found.
|
|
68
|
+
const ranked = await store.search(queryVector, filterActive ? Number.MAX_SAFE_INTEGER : topN);
|
|
69
|
+
const candidates = [];
|
|
70
|
+
for (const r of ranked) {
|
|
71
|
+
if (filterActive) {
|
|
72
|
+
const item = await store.getItem(r.id);
|
|
73
|
+
if (!matchesDateFilter(item?.metadata ?? {}, dateFilter))
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
candidates.push(r);
|
|
77
|
+
if (candidates.length >= topN)
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
if (!select) {
|
|
81
|
+
const out = await runWithConcurrency(candidates, 8, async ({ id, score }) => {
|
|
82
|
+
const item = terms.length ? await store.getItem(id) : null;
|
|
83
|
+
const result = {
|
|
84
|
+
id,
|
|
85
|
+
score,
|
|
86
|
+
view_url: client.buildIssueViewUrl(id),
|
|
87
|
+
};
|
|
88
|
+
if (terms.length && item) {
|
|
89
|
+
const h = buildHighlights(item.metadata.summary, item.metadata.description, terms);
|
|
90
|
+
if (h)
|
|
91
|
+
result.highlights = h;
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
});
|
|
95
|
+
return jsonResult(out);
|
|
96
|
+
}
|
|
97
|
+
const fields = select
|
|
98
|
+
.split(',')
|
|
99
|
+
.map((f) => f.trim())
|
|
100
|
+
.filter(Boolean);
|
|
101
|
+
// Bounded HTTP fan-out: at most topN fetches, 5 concurrent (matches mantis_get_issues).
|
|
102
|
+
const enriched = await runWithConcurrency(candidates, 5, async ({ id, score }) => {
|
|
103
|
+
const base = {
|
|
104
|
+
id,
|
|
105
|
+
score,
|
|
106
|
+
view_url: client.buildIssueViewUrl(id),
|
|
107
|
+
};
|
|
108
|
+
try {
|
|
109
|
+
const issueResult = await client.get(`/issues/${id}`);
|
|
110
|
+
const issue = issueResult.issues?.[0] ?? {};
|
|
111
|
+
for (const field of fields) {
|
|
112
|
+
if (field !== 'id' && field in issue)
|
|
113
|
+
base[field] = issue[field];
|
|
114
|
+
}
|
|
115
|
+
if (terms.length) {
|
|
116
|
+
const summary = typeof issue.summary === 'string' ? issue.summary : undefined;
|
|
117
|
+
const description = typeof issue.description === 'string' ? issue.description : undefined;
|
|
118
|
+
const h = buildHighlights(summary, description, terms);
|
|
119
|
+
if (h)
|
|
120
|
+
base.highlights = h;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// keep the bare {id, score, view_url}
|
|
125
|
+
}
|
|
126
|
+
return base;
|
|
127
|
+
});
|
|
128
|
+
return jsonResult(enriched);
|
|
129
|
+
}));
|
|
130
|
+
server.registerTool('mantis_search_index_status', {
|
|
131
|
+
title: 'Search index status',
|
|
132
|
+
description: 'Fill level of the semantic index: indexed vs. total issues, plus last sync timestamp.',
|
|
133
|
+
inputSchema: {},
|
|
134
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
|
|
135
|
+
}, handler(async () => {
|
|
136
|
+
const [indexed, lastSyncedAt, total] = await Promise.all([
|
|
137
|
+
store.count(),
|
|
138
|
+
store.getLastSyncedAt(),
|
|
139
|
+
store.getLastKnownTotal(),
|
|
140
|
+
]);
|
|
141
|
+
const percent = total !== null ? (total > 0 ? Math.round((indexed / total) * 100) : 0) : null;
|
|
142
|
+
const summary = total !== null ? `${indexed}/${total} (${percent}%)` : `${indexed}/? (total unknown)`;
|
|
143
|
+
return jsonResult({ summary, indexed, total, percent, last_synced_at: lastSyncedAt });
|
|
144
|
+
}));
|
|
145
|
+
server.registerTool('mantis_rebuild_search_index', {
|
|
146
|
+
title: 'Rebuild semantic search index',
|
|
147
|
+
description: 'Builds/updates the semantic search index from Mantis issues. Use full=true to clear and rebuild from scratch. First run downloads the embedding model (may take a minute).',
|
|
148
|
+
inputSchema: {
|
|
149
|
+
project_id: z
|
|
150
|
+
.number()
|
|
151
|
+
.int()
|
|
152
|
+
.positive()
|
|
153
|
+
.optional()
|
|
154
|
+
.describe('Only index issues from this project.'),
|
|
155
|
+
full: z
|
|
156
|
+
.preprocess(coerceBool, z.boolean().optional())
|
|
157
|
+
.describe('Clear the index and rebuild (default false).'),
|
|
158
|
+
},
|
|
159
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
|
|
160
|
+
}, handler(async ({ project_id, full }) => {
|
|
161
|
+
if (full) {
|
|
162
|
+
await store.clear();
|
|
163
|
+
await store.resetLastSyncedAt();
|
|
164
|
+
}
|
|
165
|
+
const startMs = Date.now();
|
|
166
|
+
const service = new SearchSyncService(client, store, embedder);
|
|
167
|
+
const { indexed, skipped, total } = await service.sync(project_id);
|
|
168
|
+
return jsonResult({ indexed, skipped, total, duration_ms: Date.now() - startMs });
|
|
169
|
+
}));
|
|
170
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { Embedder } from './search/embedder.js';
|
|
3
|
+
import { VectorStore } from './search/store.js';
|
|
4
|
+
import { registerSearchTools } from './search/tools.js';
|
|
5
|
+
import { registerIssueTools } from './tools/issues.js';
|
|
6
|
+
import { registerMetaTools } from './tools/meta.js';
|
|
7
|
+
import { registerNoteTools } from './tools/notes.js';
|
|
8
|
+
import { registerRelationshipTools } from './tools/relationships.js';
|
|
9
|
+
/**
|
|
10
|
+
* Builds the MCP surface over the Mantis REST client. Read tools are always
|
|
11
|
+
* registered; write tools (notes, issue updates, relationships) only when the
|
|
12
|
+
* client is not read-only. Semantic search tools are registered when enabled.
|
|
13
|
+
*/
|
|
14
|
+
export function createMcpServer(client, search) {
|
|
15
|
+
const server = new McpServer({
|
|
16
|
+
name: 'mcp-stdio-mantis-soap',
|
|
17
|
+
version: '0.3.0',
|
|
18
|
+
});
|
|
19
|
+
registerMetaTools(server, client);
|
|
20
|
+
registerIssueTools(server, client); // read tools always; write tools guarded internally
|
|
21
|
+
if (!client.isReadonly) {
|
|
22
|
+
registerNoteTools(server, client);
|
|
23
|
+
registerRelationshipTools(server, client);
|
|
24
|
+
}
|
|
25
|
+
if (search.enabled) {
|
|
26
|
+
const store = new VectorStore(search.dir);
|
|
27
|
+
const embedder = new Embedder(search.modelName, search.numThreads);
|
|
28
|
+
registerSearchTools(server, client, store, embedder);
|
|
29
|
+
}
|
|
30
|
+
return server;
|
|
31
|
+
}
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { dateFilterSchema, hasDateFilter, matchesDateFilter, } from '../date-filter.js';
|
|
3
|
+
import { postNote } from './notes.js';
|
|
4
|
+
import { customFieldEntry, enrichIssue, handler, jsonResult, ref, runWithConcurrency, unwrapIssue, } from './shared.js';
|
|
5
|
+
const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true };
|
|
6
|
+
const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false };
|
|
7
|
+
const ENUM_REF_FIELDS = [
|
|
8
|
+
'status',
|
|
9
|
+
'priority',
|
|
10
|
+
'severity',
|
|
11
|
+
'resolution',
|
|
12
|
+
'reproducibility',
|
|
13
|
+
];
|
|
14
|
+
const coerceBool = (val) => (val === 'true' ? true : val === 'false' ? false : val);
|
|
15
|
+
// Lightweight default projection for list_issues — omits the heavy notes/attachments/history
|
|
16
|
+
// arrays (a full listing of those blows past tool output limits; use mantis_get_issue for detail).
|
|
17
|
+
const LIST_DEFAULT_FIELDS = [
|
|
18
|
+
'id',
|
|
19
|
+
'summary',
|
|
20
|
+
'status',
|
|
21
|
+
'handler',
|
|
22
|
+
'reporter',
|
|
23
|
+
'priority',
|
|
24
|
+
'severity',
|
|
25
|
+
'category',
|
|
26
|
+
'project',
|
|
27
|
+
'resolution',
|
|
28
|
+
'updated_at',
|
|
29
|
+
'created_at',
|
|
30
|
+
];
|
|
31
|
+
// Fields each fetched issue must carry for the client-side filters to work.
|
|
32
|
+
const FILTER_REQUIRED_FIELDS = ['id', 'handler', 'reporter', 'status', 'updated_at', 'created_at'];
|
|
33
|
+
// Builds the `select` sent to the API: the caller's fields (or the lightweight default),
|
|
34
|
+
// always union the fields the active client-side filters depend on so filtering can't silently
|
|
35
|
+
// match nothing when the caller omits e.g. `handler`.
|
|
36
|
+
function buildApiSelect(userFields, needsClientFilter) {
|
|
37
|
+
const set = new Set(userFields ?? LIST_DEFAULT_FIELDS);
|
|
38
|
+
set.add('id');
|
|
39
|
+
if (needsClientFilter)
|
|
40
|
+
for (const f of FILTER_REQUIRED_FIELDS)
|
|
41
|
+
set.add(f);
|
|
42
|
+
return [...set].join(',');
|
|
43
|
+
}
|
|
44
|
+
// Projects an issue down to the caller's requested fields (always keeping id + view_url), so the
|
|
45
|
+
// extra fields forced in for filtering do not leak into the output when the caller asked for a subset.
|
|
46
|
+
function projectIssue(client, issue, fields) {
|
|
47
|
+
const source = issue;
|
|
48
|
+
const out = {};
|
|
49
|
+
for (const f of fields)
|
|
50
|
+
if (f in source)
|
|
51
|
+
out[f] = source[f];
|
|
52
|
+
if (issue.id !== undefined) {
|
|
53
|
+
out.id = issue.id;
|
|
54
|
+
out.view_url = client.buildIssueViewUrl(issue.id);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
// Resolves enum {name} refs to {id} in-place on a patch object.
|
|
59
|
+
async function resolveEnumRefs(client, patch) {
|
|
60
|
+
for (const group of ENUM_REF_FIELDS) {
|
|
61
|
+
const val = patch[group];
|
|
62
|
+
if (val?.name !== undefined && val.id === undefined) {
|
|
63
|
+
patch[group] = { id: await client.resolveEnumId(group, val.name) };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const fieldsSchema = z
|
|
68
|
+
.object({
|
|
69
|
+
summary: z.string().optional(),
|
|
70
|
+
description: z.string().optional(),
|
|
71
|
+
steps_to_reproduce: z.string().optional(),
|
|
72
|
+
additional_information: z.string().optional(),
|
|
73
|
+
status: ref.optional(),
|
|
74
|
+
resolution: ref.optional(),
|
|
75
|
+
priority: ref.optional(),
|
|
76
|
+
severity: ref.optional(),
|
|
77
|
+
reproducibility: ref.optional(),
|
|
78
|
+
handler: ref.optional(),
|
|
79
|
+
category: ref.optional(),
|
|
80
|
+
version: ref.optional(),
|
|
81
|
+
target_version: ref.optional(),
|
|
82
|
+
fixed_in_version: ref.optional(),
|
|
83
|
+
view_state: ref.optional(),
|
|
84
|
+
custom_fields: z.array(customFieldEntry).optional(),
|
|
85
|
+
})
|
|
86
|
+
.strict();
|
|
87
|
+
export function registerIssueTools(server, client) {
|
|
88
|
+
// --- get_issue ----------------------------------------------------------
|
|
89
|
+
server.registerTool('mantis_get_issue', {
|
|
90
|
+
title: 'Get issue',
|
|
91
|
+
description: 'Returns one issue by id with every field: description, steps to reproduce, notes, attachments, relationships, custom fields and history. Notes are always included.',
|
|
92
|
+
inputSchema: {
|
|
93
|
+
issue_id: z.number().int().positive().describe('Numeric issue id, e.g. 1239.'),
|
|
94
|
+
select: z
|
|
95
|
+
.string()
|
|
96
|
+
.optional()
|
|
97
|
+
.describe('Comma-separated fields to include (server-side projection), e.g. "id,summary,status,notes".'),
|
|
98
|
+
},
|
|
99
|
+
annotations: READ_ONLY,
|
|
100
|
+
}, handler(async ({ issue_id, select }) => {
|
|
101
|
+
const result = await client.get(`/issues/${issue_id}`, { select });
|
|
102
|
+
return jsonResult(enrichIssue(client, unwrapIssue(result, issue_id)));
|
|
103
|
+
}));
|
|
104
|
+
// --- get_issues (batch) -------------------------------------------------
|
|
105
|
+
server.registerTool('mantis_get_issues', {
|
|
106
|
+
title: 'Get multiple issues',
|
|
107
|
+
description: 'Fetch several issues by id in one call (max 5 concurrent). Missing/inaccessible ids return null at their position instead of failing the whole call. Includes requested/found/failed counters.',
|
|
108
|
+
inputSchema: {
|
|
109
|
+
ids: z
|
|
110
|
+
.array(z.number().int().positive())
|
|
111
|
+
.min(1)
|
|
112
|
+
.max(50)
|
|
113
|
+
.describe('Issue ids to fetch (1–50).'),
|
|
114
|
+
},
|
|
115
|
+
annotations: READ_ONLY,
|
|
116
|
+
}, handler(async ({ ids }) => {
|
|
117
|
+
const raw = await runWithConcurrency(ids, 5, async (id) => {
|
|
118
|
+
try {
|
|
119
|
+
const result = await client.get(`/issues/${id}`);
|
|
120
|
+
return enrichIssue(client, unwrapIssue(result, id));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
const found = raw.filter((r) => r !== null).length;
|
|
127
|
+
return jsonResult({ issues: raw, requested: ids.length, found, failed: ids.length - found });
|
|
128
|
+
}));
|
|
129
|
+
// --- list_issues --------------------------------------------------------
|
|
130
|
+
server.registerTool('mantis_list_issues', {
|
|
131
|
+
title: 'List issues',
|
|
132
|
+
description: 'List issues (newest id first). Returns a LIGHTWEIGHT summary per issue by default ' +
|
|
133
|
+
'(id, summary, status, handler, reporter, priority, dates…) — call mantis_get_issue for notes/attachments/history. ' +
|
|
134
|
+
'Filter server-side by project_id / stored filter_id. The status, assigned_to, reporter_id and date ' +
|
|
135
|
+
'filters are applied client-side (the REST API lacks them); when active, multiple pages are scanned ' +
|
|
136
|
+
'(up to 500 issues). Use status="open" for all not-yet-resolved issues. Omit project_id to span all projects.',
|
|
137
|
+
inputSchema: {
|
|
138
|
+
project_id: z.number().int().positive().optional(),
|
|
139
|
+
filter_id: z
|
|
140
|
+
.number()
|
|
141
|
+
.int()
|
|
142
|
+
.positive()
|
|
143
|
+
.optional()
|
|
144
|
+
.describe('Stored Mantis filter id (see mantis_list_filters).'),
|
|
145
|
+
page: z.number().int().positive().optional().describe('1-based page number (default 1).'),
|
|
146
|
+
page_size: z.number().int().positive().optional().describe('Issues per page (default 50).'),
|
|
147
|
+
assigned_to: z
|
|
148
|
+
.number()
|
|
149
|
+
.int()
|
|
150
|
+
.positive()
|
|
151
|
+
.optional()
|
|
152
|
+
.describe('Handler/assignee user id (client-side filter).'),
|
|
153
|
+
reporter_id: z
|
|
154
|
+
.number()
|
|
155
|
+
.int()
|
|
156
|
+
.positive()
|
|
157
|
+
.optional()
|
|
158
|
+
.describe('Reporter user id (client-side filter).'),
|
|
159
|
+
status: z
|
|
160
|
+
.string()
|
|
161
|
+
.optional()
|
|
162
|
+
.describe('Status name (localized or canonical) or "open" for all not-yet-resolved issues (client-side).'),
|
|
163
|
+
select: z
|
|
164
|
+
.string()
|
|
165
|
+
.optional()
|
|
166
|
+
.describe('Comma-separated fields to include. Defaults to a lightweight summary set. ' +
|
|
167
|
+
'Fields needed by the active filters are always fetched even if omitted here.'),
|
|
168
|
+
...dateFilterSchema,
|
|
169
|
+
},
|
|
170
|
+
annotations: READ_ONLY,
|
|
171
|
+
}, handler(async ({ project_id, filter_id, page = 1, page_size, assigned_to, reporter_id, status, select, updated_after, updated_before, created_after, created_before, }) => {
|
|
172
|
+
const pageSize = client.clampPageSize(page_size);
|
|
173
|
+
const dateFilter = {
|
|
174
|
+
updated_after,
|
|
175
|
+
updated_before,
|
|
176
|
+
created_after,
|
|
177
|
+
created_before,
|
|
178
|
+
};
|
|
179
|
+
const needsClientFilter = status !== undefined ||
|
|
180
|
+
assigned_to !== undefined ||
|
|
181
|
+
reporter_id !== undefined ||
|
|
182
|
+
hasDateFilter(dateFilter);
|
|
183
|
+
const userFields = select
|
|
184
|
+
? select
|
|
185
|
+
.split(',')
|
|
186
|
+
.map((f) => f.trim())
|
|
187
|
+
.filter(Boolean)
|
|
188
|
+
: null;
|
|
189
|
+
const apiSelect = buildApiSelect(userFields, needsClientFilter);
|
|
190
|
+
// Shape output: project to the caller's fields when given, else the lightweight default.
|
|
191
|
+
const shape = (issue) => userFields ? projectIssue(client, issue, userFields) : enrichIssue(client, issue);
|
|
192
|
+
if (!needsClientFilter) {
|
|
193
|
+
const result = await client.get('/issues', {
|
|
194
|
+
project_id,
|
|
195
|
+
filter_id,
|
|
196
|
+
select: apiSelect,
|
|
197
|
+
page,
|
|
198
|
+
page_size: pageSize,
|
|
199
|
+
});
|
|
200
|
+
return jsonResult({ issues: (result.issues ?? []).map(shape) });
|
|
201
|
+
}
|
|
202
|
+
// Client-side filtering: scan API pages until enough matches for page N.
|
|
203
|
+
const API_PAGE_SIZE = 50;
|
|
204
|
+
const MAX_API_PAGES = 10; // scan at most 500 issues
|
|
205
|
+
const neededTotal = page * pageSize;
|
|
206
|
+
const statusLower = status?.toLowerCase();
|
|
207
|
+
const statusId = status !== undefined && status.toLowerCase() !== 'open'
|
|
208
|
+
? await client.resolveEnumId('status', status).catch(() => undefined)
|
|
209
|
+
: undefined;
|
|
210
|
+
const threshold = statusLower === 'open' ? await client.getResolvedStatusThreshold() : 0;
|
|
211
|
+
const matching = [];
|
|
212
|
+
let serverPage = 1;
|
|
213
|
+
let hasMore = true;
|
|
214
|
+
while (matching.length < neededTotal && serverPage <= MAX_API_PAGES && hasMore) {
|
|
215
|
+
const batch = await client.get('/issues', {
|
|
216
|
+
project_id,
|
|
217
|
+
filter_id,
|
|
218
|
+
select: apiSelect,
|
|
219
|
+
page: serverPage,
|
|
220
|
+
page_size: API_PAGE_SIZE,
|
|
221
|
+
});
|
|
222
|
+
const issues = batch.issues ?? [];
|
|
223
|
+
hasMore = issues.length === API_PAGE_SIZE;
|
|
224
|
+
for (const issue of issues) {
|
|
225
|
+
if (statusLower) {
|
|
226
|
+
if (!issue.status)
|
|
227
|
+
continue;
|
|
228
|
+
if (statusLower === 'open') {
|
|
229
|
+
if ((issue.status.id ?? 0) >= threshold)
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
else if (statusId !== undefined) {
|
|
233
|
+
if (issue.status.id !== statusId)
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
else if ((issue.status.name ?? '').toLowerCase() !== statusLower) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (assigned_to !== undefined && issue.handler?.id !== assigned_to)
|
|
241
|
+
continue;
|
|
242
|
+
if (reporter_id !== undefined && issue.reporter?.id !== reporter_id)
|
|
243
|
+
continue;
|
|
244
|
+
if (!matchesDateFilter(issue, dateFilter))
|
|
245
|
+
continue;
|
|
246
|
+
matching.push(issue);
|
|
247
|
+
}
|
|
248
|
+
serverPage++;
|
|
249
|
+
}
|
|
250
|
+
const start = (page - 1) * pageSize;
|
|
251
|
+
const pageIssues = matching.slice(start, start + pageSize).map(shape);
|
|
252
|
+
return jsonResult({
|
|
253
|
+
issues: pageIssues,
|
|
254
|
+
scanned_pages: serverPage - 1,
|
|
255
|
+
matched: matching.length,
|
|
256
|
+
});
|
|
257
|
+
}));
|
|
258
|
+
// --- get_issue_attachment ----------------------------------------------
|
|
259
|
+
server.registerTool('mantis_get_issue_attachment', {
|
|
260
|
+
title: 'Get issue attachment',
|
|
261
|
+
description: 'Downloads an attachment of an issue. Image attachments are returned as a viewable image; other files as base64 with metadata. Find file ids in an issue\'s "attachments" array.',
|
|
262
|
+
inputSchema: {
|
|
263
|
+
issue_id: z.number().int().positive(),
|
|
264
|
+
file_id: z
|
|
265
|
+
.number()
|
|
266
|
+
.int()
|
|
267
|
+
.positive()
|
|
268
|
+
.describe('Attachment id from the issue "attachments" array.'),
|
|
269
|
+
},
|
|
270
|
+
annotations: READ_ONLY,
|
|
271
|
+
}, handler(async ({ issue_id, file_id }) => {
|
|
272
|
+
const file = await client.getAttachment(issue_id, file_id);
|
|
273
|
+
const meta = {
|
|
274
|
+
id: file.id,
|
|
275
|
+
filename: file.filename,
|
|
276
|
+
size: file.size,
|
|
277
|
+
content_type: file.contentType,
|
|
278
|
+
issue_id,
|
|
279
|
+
view_url: client.buildIssueViewUrl(issue_id),
|
|
280
|
+
};
|
|
281
|
+
if (file.mediaType.startsWith('image/')) {
|
|
282
|
+
return {
|
|
283
|
+
content: [
|
|
284
|
+
{ type: 'image', data: file.base64, mimeType: file.mediaType },
|
|
285
|
+
{ type: 'text', text: JSON.stringify(meta) },
|
|
286
|
+
],
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
content: [
|
|
291
|
+
{ type: 'text', text: JSON.stringify(meta) },
|
|
292
|
+
{ type: 'text', text: `base64:${file.base64}` },
|
|
293
|
+
],
|
|
294
|
+
};
|
|
295
|
+
}));
|
|
296
|
+
// Write tools are only registered when not in read-only mode.
|
|
297
|
+
if (client.isReadonly)
|
|
298
|
+
return;
|
|
299
|
+
// --- update_issue -------------------------------------------------------
|
|
300
|
+
server.registerTool('mantis_update_issue', {
|
|
301
|
+
title: 'Update issue',
|
|
302
|
+
description: `Partial update of an issue (PATCH). The "fields" object accepts any of:
|
|
303
|
+
- summary, description, steps_to_reproduce, additional_information (strings)
|
|
304
|
+
- status, resolution, priority, severity, reproducibility: { name } (localized or canonical) or { id }
|
|
305
|
+
- handler: { name: "<login>" } or { id }
|
|
306
|
+
- category, version, target_version, fixed_in_version, view_state: { name }
|
|
307
|
+
- custom_fields: [{ field: {id|name}, value: "<string>" }]
|
|
308
|
+
|
|
309
|
+
When resolving an issue set BOTH status and resolution (or use mantis_resolve_issue). Use "note" to append a comment (e.g. the reason for the change) in the same call. Use dry_run to preview the payload.`,
|
|
310
|
+
inputSchema: {
|
|
311
|
+
id: z.number().int().positive().describe('Numeric issue id to update.'),
|
|
312
|
+
fields: z.preprocess((v) => {
|
|
313
|
+
if (typeof v !== 'string')
|
|
314
|
+
return v;
|
|
315
|
+
try {
|
|
316
|
+
return JSON.parse(v);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
return v;
|
|
320
|
+
}
|
|
321
|
+
}, fieldsSchema),
|
|
322
|
+
note: z
|
|
323
|
+
.string()
|
|
324
|
+
.min(1)
|
|
325
|
+
.optional()
|
|
326
|
+
.describe('Optional note appended after a successful update.'),
|
|
327
|
+
note_private: z
|
|
328
|
+
.boolean()
|
|
329
|
+
.optional()
|
|
330
|
+
.describe('Make the appended note private (default false).'),
|
|
331
|
+
dry_run: z
|
|
332
|
+
.preprocess(coerceBool, z.boolean().optional())
|
|
333
|
+
.describe('If true, return the patch that would be sent without applying it.'),
|
|
334
|
+
},
|
|
335
|
+
annotations: WRITE,
|
|
336
|
+
}, handler(async ({ id, fields, note, note_private, dry_run }) => {
|
|
337
|
+
const patch = { ...fields };
|
|
338
|
+
await resolveEnumRefs(client, patch);
|
|
339
|
+
// Resolve handler login name -> id (needs the issue's project).
|
|
340
|
+
const handlerRef = patch.handler;
|
|
341
|
+
if (handlerRef?.name !== undefined && handlerRef.id === undefined) {
|
|
342
|
+
const current = await client.get(`/issues/${id}`, {
|
|
343
|
+
select: 'id,project',
|
|
344
|
+
});
|
|
345
|
+
const projectId = current.issues?.[0]?.project?.id;
|
|
346
|
+
if (projectId === undefined)
|
|
347
|
+
throw new Error(`Cannot resolve handler: issue ${id} has no project.`);
|
|
348
|
+
patch.handler = { id: await client.resolveHandlerId(projectId, handlerRef.name) };
|
|
349
|
+
}
|
|
350
|
+
if (dry_run) {
|
|
351
|
+
return jsonResult({ dry_run: true, id, would_patch: patch, would_add_note: note ?? null });
|
|
352
|
+
}
|
|
353
|
+
const result = await client.patch(`/issues/${id}`, patch);
|
|
354
|
+
const response = { ...enrichIssue(client, unwrapIssue(result, id)) };
|
|
355
|
+
if (note !== undefined) {
|
|
356
|
+
// PATCH already succeeded — a note failure must not look like a failed update.
|
|
357
|
+
try {
|
|
358
|
+
response.note = await postNote(client, id, note, note_private ? 'private' : 'public');
|
|
359
|
+
}
|
|
360
|
+
catch (noteError) {
|
|
361
|
+
const msg = noteError instanceof Error ? noteError.message : String(noteError);
|
|
362
|
+
response.note_error = `Issue #${id} was updated, but adding the note failed: ${msg}. Retry with mantis_add_note.`;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return jsonResult(response);
|
|
366
|
+
}));
|
|
367
|
+
// --- resolve_issue ------------------------------------------------------
|
|
368
|
+
server.registerTool('mantis_resolve_issue', {
|
|
369
|
+
title: 'Resolve issue',
|
|
370
|
+
description: 'Marks an issue as resolved by setting BOTH status and resolution in one call (avoids leaving resolution as "open"). ' +
|
|
371
|
+
'Defaults: status="resuelta", resolution="fixed" — override with names valid on this instance (see mantis_get_enums). Optionally append a note.',
|
|
372
|
+
inputSchema: {
|
|
373
|
+
id: z.number().int().positive().describe('Numeric issue id to resolve.'),
|
|
374
|
+
status: z.string().optional().describe('Target status name (default "resuelta").'),
|
|
375
|
+
resolution: z.string().optional().describe('Resolution name (default "fixed").'),
|
|
376
|
+
note: z.string().min(1).optional().describe('Optional note explaining the resolution.'),
|
|
377
|
+
note_private: z.boolean().optional().describe('Make the note private (default false).'),
|
|
378
|
+
dry_run: z
|
|
379
|
+
.preprocess(coerceBool, z.boolean().optional())
|
|
380
|
+
.describe('Preview without applying.'),
|
|
381
|
+
},
|
|
382
|
+
annotations: WRITE,
|
|
383
|
+
}, handler(async ({ id, status, resolution, note, note_private, dry_run }) => {
|
|
384
|
+
const patch = {
|
|
385
|
+
status: { id: await client.resolveEnumId('status', status ?? 'resuelta') },
|
|
386
|
+
resolution: { id: await client.resolveEnumId('resolution', resolution ?? 'fixed') },
|
|
387
|
+
};
|
|
388
|
+
if (dry_run) {
|
|
389
|
+
return jsonResult({ dry_run: true, id, would_patch: patch, would_add_note: note ?? null });
|
|
390
|
+
}
|
|
391
|
+
const result = await client.patch(`/issues/${id}`, patch);
|
|
392
|
+
const response = { ...enrichIssue(client, unwrapIssue(result, id)) };
|
|
393
|
+
if (note !== undefined) {
|
|
394
|
+
try {
|
|
395
|
+
response.note = await postNote(client, id, note, note_private ? 'private' : 'public');
|
|
396
|
+
}
|
|
397
|
+
catch (noteError) {
|
|
398
|
+
const msg = noteError instanceof Error ? noteError.message : String(noteError);
|
|
399
|
+
response.note_error = `Issue #${id} was resolved, but adding the note failed: ${msg}.`;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return jsonResult(response);
|
|
403
|
+
}));
|
|
404
|
+
// --- assign_issue -------------------------------------------------------
|
|
405
|
+
server.registerTool('mantis_assign_issue', {
|
|
406
|
+
title: 'Assign issue',
|
|
407
|
+
description: 'Assigns an issue to a handler (by login name or user id) and optionally changes its status in the same call. Optionally append a note.',
|
|
408
|
+
inputSchema: {
|
|
409
|
+
id: z.number().int().positive().describe('Numeric issue id.'),
|
|
410
|
+
handler: z
|
|
411
|
+
.union([z.string(), z.number().int().positive()])
|
|
412
|
+
.describe('Handler login name (resolved via project members) or numeric user id.'),
|
|
413
|
+
status: z.string().optional().describe('Optional new status name (e.g. "asignada").'),
|
|
414
|
+
note: z.string().min(1).optional().describe('Optional note.'),
|
|
415
|
+
note_private: z.boolean().optional().describe('Make the note private (default false).'),
|
|
416
|
+
dry_run: z
|
|
417
|
+
.preprocess(coerceBool, z.boolean().optional())
|
|
418
|
+
.describe('Preview without applying.'),
|
|
419
|
+
},
|
|
420
|
+
annotations: WRITE,
|
|
421
|
+
}, handler(async ({ id, handler: handlerValue, status, note, note_private, dry_run }) => {
|
|
422
|
+
const current = await client.get(`/issues/${id}`, {
|
|
423
|
+
select: 'id,project',
|
|
424
|
+
});
|
|
425
|
+
const projectId = current.issues?.[0]?.project?.id;
|
|
426
|
+
if (projectId === undefined)
|
|
427
|
+
throw new Error(`Cannot assign: issue ${id} has no project.`);
|
|
428
|
+
const handlerId = await client.resolveHandlerId(projectId, handlerValue);
|
|
429
|
+
const patch = { handler: { id: handlerId } };
|
|
430
|
+
if (status !== undefined)
|
|
431
|
+
patch.status = { id: await client.resolveEnumId('status', status) };
|
|
432
|
+
if (dry_run) {
|
|
433
|
+
return jsonResult({ dry_run: true, id, would_patch: patch, would_add_note: note ?? null });
|
|
434
|
+
}
|
|
435
|
+
const result = await client.patch(`/issues/${id}`, patch);
|
|
436
|
+
const response = { ...enrichIssue(client, unwrapIssue(result, id)) };
|
|
437
|
+
if (note !== undefined) {
|
|
438
|
+
try {
|
|
439
|
+
response.note = await postNote(client, id, note, note_private ? 'private' : 'public');
|
|
440
|
+
}
|
|
441
|
+
catch (noteError) {
|
|
442
|
+
const msg = noteError instanceof Error ? noteError.message : String(noteError);
|
|
443
|
+
response.note_error = `Issue #${id} was assigned, but adding the note failed: ${msg}.`;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return jsonResult(response);
|
|
447
|
+
}));
|
|
448
|
+
}
|