-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
183 lines (164 loc) · 4.8 KB
/
index.ts
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
import fetch from 'node-fetch';
import process from 'node:process';
const GLEAN_API_KEY = process.env.GLEAN_API_KEY!;
const GLEAN_DOMAIN = process.env.GLEAN_DOMAIN!;
type Fragment = {
text?: string;
};
type Citation = {
sourceDocument?: { title?: string; url?: string };
sourcePerson?: { name?: string };
};
type Message = {
messageType?: string;
fragments?: Fragment[];
citations?: Citation[];
};
type ApiResponse = {
messages?: Message[];
};
// Define the search tool
const SEARCH_TOOL: Tool = {
name: "search",
description: "Tool to perform search queries using Glean API",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "The query to perform retrieval on" },
},
required: ["query"],
},
};
// Define the ChatGPT tool
const CHATGPT_TOOL: Tool = {
name: "chat",
description: "Tool to interact with ChatGPT using Glean API",
inputSchema: {
type: "object",
properties: {
message: { type: "string", description: "The message to send to ChatGPT" },
},
required: ["message"],
},
};
// Server setup
const server = new Server(
{
name: "glean-server",
version: "0.1.0",
},
{
capabilities: {
tools: {
search: SEARCH_TOOL,
chatgpt: CHATGPT_TOOL,
},
},
},
);
// Request handlers
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [SEARCH_TOOL, CHATGPT_TOOL],
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (name === "search") {
const { query } = args as Record<string, any>;
try {
const response = await fetch(`https://${GLEAN_DOMAIN}-be.glean.com/rest/api/v1/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${GLEAN_API_KEY}`,
},
body: JSON.stringify({ query }),
});
const result = await response.json();
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
} catch (error) {
return {
content: [{ type: "text", text: `Error occurred: ${error}` }],
};
}
} else if (name === "chat") {
const { message } = args as Record<string, any>;
const response = await fetch(`https://${GLEAN_DOMAIN}-be.glean.com/rest/api/v1/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${GLEAN_API_KEY}`,
},
body: JSON.stringify({
stream: false,
messages: [{
author: 'USER',
fragments: [{ text: message }]
}],
}),
});
if (response.ok) {
const data: unknown = await response.json();
// Validate and typecast `data`
if (typeof data === 'object' && data !== null && 'messages' in data) {
const apiResponse = data as ApiResponse;
const messages = apiResponse.messages || [];
let result = '';
for (const message of messages) {
if (message.messageType === 'CONTENT') {
message.fragments?.forEach((fragment: Fragment) => {
result += fragment.text || '';
});
if (message.citations?.length) {
result += '\nSources:\n';
message.citations.forEach((citation: Citation, idx: number) => {
if (citation.sourceDocument?.title && citation.sourceDocument?.url) {
result += `Source ${idx + 1}: ${citation.sourceDocument.title} (${citation.sourceDocument.url})\n`;
}
if (citation.sourcePerson?.name) {
result += `Source ${idx + 1}: ${citation.sourcePerson.name}\n`;
}
});
}
}
}
return {
content: [{ type: 'text', text: result }],
};
} else {
throw new Error('Unexpected API response structure');
}
} else {
const errorText = await response.text();
return {
content: [{ type: 'text', text: `Error: ${response.status} - ${errorText}` }],
isError: true,
};
}
}
else {
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
}
});
// Server startup
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Glean Server running on stdio");
}
runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});