Skip to content

Commit ca0f073

Browse files
committed
📦 NEW: Docs MCP Server
1 parent 6598233 commit ca0f073

File tree

5 files changed

+233
-2
lines changed

5 files changed

+233
-2
lines changed

packages/cli/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
"@clack/prompts": "^0.7.0",
5252
"@hono/node-server": "^1.13.1",
5353
"@hono/zod-openapi": "^0.16.0",
54+
"@modelcontextprotocol/sdk": "^1.8.0",
5455
"@sindresorhus/slugify": "^2.2.1",
5556
"camelcase": "^8.0.0",
5657
"chalk": "^5.3.0",
@@ -71,6 +72,7 @@
7172
"get-package-json-file": "^2.0.0",
7273
"hono": "^4.5.11",
7374
"js-tiktoken": "^1.0.14",
75+
"jsdom": "^24.1.0",
7476
"log-symbols": "^7.0.0",
7577
"lowdb": "^7.0.1",
7678
"meow": "^13.2.0",
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { JSDOM } from 'jsdom';
2+
// Fetches a list of all the docs on the langbase website
3+
export async function fetchDocsList() {
4+
try {
5+
const response = await fetch('https://langbase.com/docs/llms.txt');
6+
7+
if (!response.ok) {
8+
throw new Error('Failed to fetch docs');
9+
}
10+
11+
const text = await response.text();
12+
return text;
13+
14+
} catch (error) {
15+
throw new Error('Failed to fetch docs ' + JSON.stringify(error));
16+
}
17+
}
18+
19+
20+
// Helper function to fetch and convert a blog post to markdown
21+
export async function fetchDocsPost(url: string): Promise<string> {
22+
try {
23+
const response = await fetch(url);
24+
if (!response.ok) {
25+
throw new Error('Failed to fetch blog post');
26+
}
27+
28+
const html = await response.text();
29+
30+
const dom = new JSDOM(html);
31+
const document = dom.window.document;
32+
// Remove Next.js initialization code
33+
const scripts = document.querySelectorAll('script');
34+
scripts.forEach(script => script.remove());
35+
36+
// Get the main content
37+
const content = document.body.textContent?.trim() || '';
38+
if (!content) {
39+
throw new Error('No content found in docs');
40+
}
41+
42+
return content;
43+
} catch (error) {
44+
throw new Error(`Failed to fetch docs: ${error instanceof Error ? error.message : 'Unknown error'}`);
45+
}
46+
}
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3+
import { z } from "zod";
4+
import { fetchDocsList, fetchDocsPost } from "./docs"
5+
6+
7+
export async function docsMcpServer() {
8+
// Create server instance with resource support
9+
const server = new McpServer({
10+
name: "langbase-docs-server",
11+
version: "1.0.0"
12+
});
13+
14+
15+
// SDK-specific tool
16+
server.tool(
17+
"docs-route-finder",
18+
"Searches through all available documentation routes and returns relevant paths based on the user's query. This tool helps navigate the documentation by finding the most appropriate sections that match the search criteria.",
19+
{
20+
query: z.string().describe(`A refined search term extracted from the user's question.
21+
For example, if user asks 'How do I create a pipe?', the query would be 'SDK Pipe'.
22+
This should be the specific concept or topic to search for in the documentation.
23+
Treat keyword add as create if user ask for Eg. 'How do I add memory to pipe?' the query should be 'create memory'`),
24+
},
25+
async ({ query }) => {
26+
const docs = await fetchDocsList()
27+
// search through the docs and return the most relevent path based on the query
28+
// Split docs into lines and create an array of documentation entries
29+
const docLines = docs.split('\n').filter(line => line.trim());
30+
31+
// Create a simple scoring system for relevance
32+
const getRelevanceScore = (line: string, searchQuery: string) => {
33+
const lowerLine = line.toLowerCase();
34+
const lowerQuery = searchQuery.toLowerCase();
35+
// Higher score for exact matches
36+
if (lowerLine.includes(lowerQuery)) {
37+
return 3;
38+
}
39+
40+
// Score based on word matches
41+
const queryWords = lowerQuery.split(' ');
42+
return queryWords.reduce((score, word) => {
43+
return score + (lowerLine.includes(word) ? 1 : 0);
44+
}, 0);
45+
};
46+
47+
// Score and sort the documentation entries
48+
const scoredDocs = docLines
49+
.map(line => ({
50+
line,
51+
score: getRelevanceScore(line, query)
52+
}))
53+
.sort((a, b) => b.score - a.score)
54+
.filter(doc => doc.score > 0)
55+
.slice(0, 3); // Get top 3 most relevant results
56+
57+
58+
if (scoredDocs.length === 0) {
59+
return {
60+
content: [{
61+
type: "text",
62+
text: "No relevant documentation found for the query: " + query
63+
}]
64+
};
65+
}
66+
67+
// Extract URLs and create formatted response
68+
const results = scoredDocs.map(doc => doc.line).join('\n');
69+
70+
return {
71+
content: [
72+
{
73+
type: "text",
74+
text: results,
75+
},
76+
],
77+
};
78+
}
79+
);
80+
81+
82+
server.tool(
83+
"sdk-documentation-fetcher",
84+
"Fetches detailed SDK documentation, specializing in implementation guides for core features like pipes, memory, and tools. This is the primary source for the latest SDK documentation and should be consulted first for questions about creating or implementing SDK components. Use this tool for detailed step-by-step instructions on building pipes, configuring memory systems, and developing custom tools.",
85+
{
86+
url: z.string().describe("URL of a specific SDK page to fetch. Format: /sdk/..."),
87+
},
88+
async ({ url }) => {
89+
const content = await fetchDocsPost(`https://langbase.com/docs${url}`);
90+
return {
91+
content: [
92+
{
93+
type: "text",
94+
text: content,
95+
},
96+
],
97+
};
98+
}
99+
);
100+
101+
server.tool(
102+
"examples-tool",
103+
"Fetches code examples and sample implementations from the documentation. Use this tool when users specifically request examples, sample code, or implementation demonstrations. This tool provides practical code snippets and complete working examples that demonstrate how to implement various features.",
104+
{
105+
url: z.string().describe("URL of a specific examples page to fetch. Format: /examples/..."),
106+
},
107+
async ({ url }) => {
108+
const content = await fetchDocsPost(`https://langbase.com/docs${url}`);
109+
return {
110+
content: [
111+
{
112+
type: "text",
113+
text: content,
114+
},
115+
],
116+
};
117+
}
118+
);
119+
120+
server.tool(
121+
"guide-tool",
122+
"Fetches detailed guides and tutorials from the documentation. Use this tool when users explicitly request guides, tutorials, or how-to content. This tool provides step-by-step instructions and practical examples for implementing various features.",
123+
{
124+
url: z.string().describe("URL of a specific guide page to fetch. Format: /guides/..."),
125+
},
126+
async ({ url }) => {
127+
const content = await fetchDocsPost(`https://langbase.com/docs${url}`);
128+
return {
129+
content: [
130+
{
131+
type: "text",
132+
text: content,
133+
},
134+
],
135+
};
136+
}
137+
);
138+
139+
server.tool(
140+
"api-reference-tool",
141+
"Fetches API reference documentation. Use this tool ONLY when the user explicitly asks about API endpoints, REST API calls, or programmatically creating/updating/deleting resources (like pipes, memory, etc.) through the API interface. For general SDK implementation questions, use the sdk-documentation-fetcher instead.",
142+
{
143+
url: z.string().describe("URL of a specific api-reference page to fetch. Format: /api-reference/..."),
144+
},
145+
async ({ url }) => {
146+
const content = await fetchDocsPost(`https://langbase.com/docs${url}`);
147+
return {
148+
content: [
149+
{
150+
type: "text",
151+
text: content,
152+
},
153+
],
154+
};
155+
}
156+
);
157+
158+
159+
async function main() {
160+
const transport = new StdioServerTransport();
161+
162+
try {
163+
await server.connect(transport);
164+
console.error("Langbase service MCP Server running on stdio");
165+
} catch (error) {
166+
console.error("Error connecting to transport:", error);
167+
process.exit(1);
168+
}
169+
}
170+
171+
main().catch((error) => {
172+
console.error("Fatal error in main():", error);
173+
process.exit(1);
174+
});
175+
176+
}
177+

packages/cli/src/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { auth } from './auth';
33
import { build } from './build';
44
import { deploy } from './deploy';
5+
import { docsMcpServer } from './docs-mcp-server';
56
import cli from './utils/cli';
67
import debugMode from './utils/debug-mode';
78
import cliInit from './utils/init';
@@ -42,4 +43,8 @@ const flag = (flg: string): boolean => Boolean(flags[flg]);
4243

4344
await deploy({ isDev, agent, filePath, apiKey });
4445
}
46+
47+
if (command('docs-mcp-server')) {
48+
await docsMcpServer();
49+
}
4550
})();

packages/cli/src/utils/cli.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ const flags = {
3333
const commands = {
3434
auth: { desc: `Authenticate with Langbase` },
3535
deploy: { desc: `Deploy a script to Langbase` },
36-
help: { desc: `Print help info` }
36+
help: { desc: `Print help info` },
3737
};
3838

3939
const helpText = meowHelp({
40-
name: `baseai`,
40+
name: `langbase`,
4141
flags,
4242
commands,
4343
desc: false,
@@ -53,4 +53,5 @@ const options = {
5353
flags
5454
};
5555

56+
5657
export default meow(helpText, options);

0 commit comments

Comments
 (0)