-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetDocumentTool.ts
More file actions
95 lines (84 loc) · 2.7 KB
/
GetDocumentTool.ts
File metadata and controls
95 lines (84 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright (c) Mapbox, Inc.
// Licensed under the MIT License.
import { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import {
docCache,
MAX_ENTRY_BYTES,
readBodyWithLimit
} from '../../utils/docCache.js';
import type { HttpRequest } from '../../utils/types.js';
import { BaseTool } from '../BaseTool.js';
import {
GetDocumentSchema,
GetDocumentInput
} from './GetDocumentTool.input.schema.js';
function isMapboxUrl(url: string): boolean {
try {
const { hostname } = new URL(url);
return hostname === 'mapbox.com' || hostname.endsWith('.mapbox.com');
} catch {
return false;
}
}
export class GetDocumentTool extends BaseTool<typeof GetDocumentSchema> {
name = 'get_document_tool';
description =
'Fetch the full content of a specific Mapbox documentation page by URL. Use this after get_latest_mapbox_docs_tool to follow a link from the index and retrieve the complete page content. For fetching multiple pages at once, use batch_get_documents_tool instead.';
readonly annotations = {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
title: 'Get Mapbox Document Tool'
};
private httpRequest: HttpRequest;
constructor(params: { httpRequest: HttpRequest }) {
super({ inputSchema: GetDocumentSchema });
this.httpRequest = params.httpRequest;
}
protected async execute(input: GetDocumentInput): Promise<CallToolResult> {
if (!isMapboxUrl(input.url)) {
return {
content: [
{
type: 'text',
text: `Invalid URL: only mapbox.com URLs are supported. Received: ${input.url}`
}
],
isError: true
};
}
const cached = docCache.get(input.url);
if (cached !== null) {
return { content: [{ type: 'text', text: cached }], isError: false };
}
try {
const response = await this.httpRequest(input.url, {
headers: { Accept: 'text/markdown, text/plain;q=0.9, */*;q=0.8' }
});
if (!response.ok) {
return {
content: [
{
type: 'text',
text: `Failed to fetch document: ${response.status} ${response.statusText}`
}
],
isError: true
};
}
const content = await readBodyWithLimit(response, MAX_ENTRY_BYTES);
docCache.set(input.url, content);
return { content: [{ type: 'text', text: content }], isError: false };
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error occurred';
return {
content: [
{ type: 'text', text: `Failed to fetch document: ${errorMessage}` }
],
isError: true
};
}
}
}