openliate 0.0.1 → 0.1.5

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.
Files changed (73) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +73 -241
  3. package/README.npm.md +128 -0
  4. package/dist/bin.js +24634 -42274
  5. package/dist/liate.js +39468 -0
  6. package/dist/runtime/hono.js +28061 -0
  7. package/dist/runtime/index.js +28061 -0
  8. package/hub/agents/docgyan-agent/agent.json +27 -0
  9. package/hub/agents/docgyan-agent/agent.ts +39 -0
  10. package/hub/agents/gnani-agent/agent.json +17 -0
  11. package/hub/agents/neon-agent/agent.json +18 -0
  12. package/hub/agents/prism-agent/agent.json +17 -0
  13. package/hub/agents/sarvam-agent/agent.json +1 -3
  14. package/package.json +33 -21
  15. package/src/cli/index.ts +346 -0
  16. package/src/cli/resolver.ts +153 -0
  17. package/src/core/aum.ts +87 -28
  18. package/src/core/om.ts +159 -0
  19. package/src/core/spec.ts +112 -0
  20. package/src/core/uuid.ts +5 -16
  21. package/src/core/version.ts +2 -0
  22. package/src/layers/agent/harness.ts +118 -0
  23. package/src/{agent → layers/agent}/loop.ts +44 -24
  24. package/src/layers/agent/skills.ts +302 -0
  25. package/src/{agent → layers/agent}/types.ts +14 -1
  26. package/src/{environment/environment.ts → layers/environment/sandbox.ts} +24 -5
  27. package/src/{environment → layers/environment}/types.ts +8 -0
  28. package/src/layers/integration/knowledge.ts +187 -0
  29. package/src/layers/integration/lib.ts +167 -0
  30. package/src/{integration → layers/integration}/memory.ts +49 -67
  31. package/src/layers/integration/repo.ts +273 -0
  32. package/src/{integration → layers/integration}/types.ts +60 -31
  33. package/src/layers/llm/model.ts +916 -0
  34. package/src/layers/llm/types.ts +64 -0
  35. package/src/{tools → layers/tools}/mcp.ts +24 -10
  36. package/src/layers/tools/registry.ts +307 -0
  37. package/src/{tools → layers/tools}/server.ts +12 -13
  38. package/src/{tools → layers/tools}/types.ts +3 -2
  39. package/src/liate.ts +64 -24
  40. package/src/routes/skills.ts +73 -0
  41. package/src/runtime/hono.ts +346 -0
  42. package/src/runtime/wasm.ts +23 -0
  43. package/src/scaffold/project.ts +188 -0
  44. package/dist/engine/engine.zip +0 -0
  45. package/dist/engine/index.js +0 -36790
  46. package/hub/agents/email-agent/agent.json +0 -19
  47. package/hub/agents/general-agent/agent.json +0 -18
  48. package/hub/agents/identity-agent/agent.json +0 -19
  49. package/hub/agents/research-agent/agent.json +0 -18
  50. package/hub/llm/sarvam.json +0 -27
  51. package/hub/mcp/agentmail.json +0 -10
  52. package/hub/mcp/fetch.json +0 -9
  53. package/hub/mcp/neon.json +0 -12
  54. package/hub/mcp/sarvam.json +0 -12
  55. package/hub/mcp/supabase.json +0 -12
  56. package/hub/mcp/vercel.json +0 -12
  57. package/src/agent/agent.ts +0 -165
  58. package/src/cli.ts +0 -272
  59. package/src/engine/types.ts +0 -104
  60. package/src/integration/integration.ts +0 -37
  61. package/src/link/index.ts +0 -317
  62. package/src/link/neon.ts +0 -646
  63. package/src/link/supabase.ts +0 -567
  64. package/src/link/vercel.ts +0 -633
  65. package/src/llm/config.ts +0 -46
  66. package/src/llm/hub.ts +0 -59
  67. package/src/llm/llm.ts +0 -60
  68. package/src/llm/sarvam.ts +0 -136
  69. package/src/server/engine.ts +0 -277
  70. package/src/server/index.ts +0 -32
  71. package/src/tools/builtin/fetch.ts +0 -66
  72. package/src/tools/builtin/identity.ts +0 -131
  73. package/src/tools/registry.ts +0 -218
package/src/llm/hub.ts DELETED
@@ -1,59 +0,0 @@
1
- import { readFileSync, existsSync } from "fs";
2
- import { resolve, join } from "path";
3
- import sarvamDef from "../../hub/llm/sarvam.json";
4
-
5
- export interface HubLLMDefinition {
6
- name: string;
7
- provider: string;
8
- version: string;
9
- base_url: string;
10
- endpoint: string;
11
- default_model: string;
12
- available_models: string[];
13
- headers: Record<string, string>;
14
- features: {
15
- tool_calling: boolean;
16
- streaming: boolean;
17
- reasoning: boolean;
18
- };
19
- }
20
-
21
- export class HubResolver {
22
- private static cache: Map<string, HubLLMDefinition> = new Map();
23
-
24
- /**
25
- * Resolves a provider definition dynamically from the hub/llm/ directory.
26
- * Throws an error if the hub file does not exist, guaranteeing zero hardcoding.
27
- */
28
- public static loadLLM(providerName: string): HubLLMDefinition {
29
- if (this.cache.has(providerName)) {
30
- return this.cache.get(providerName)!;
31
- }
32
-
33
- const possiblePaths = [
34
- resolve(process.cwd(), "hub", "llm", `${providerName}.json`),
35
- resolve(process.cwd(), "..", "hub", "llm", `${providerName}.json`),
36
- join(__dirname, "..", "..", "hub", "llm", `${providerName}.json`)
37
- ];
38
-
39
- for (const filePath of possiblePaths) {
40
- if (existsSync(filePath)) {
41
- try {
42
- const content = readFileSync(filePath, "utf-8");
43
- const def = JSON.parse(content) as HubLLMDefinition;
44
- this.cache.set(providerName, def);
45
- return def;
46
- } catch (err: any) {
47
- throw new Error(`Failed to parse hub definition at ${filePath}: ${err.message}`);
48
- }
49
- }
50
- }
51
-
52
- if (providerName === "sarvam") {
53
- this.cache.set(providerName, sarvamDef as HubLLMDefinition);
54
- return sarvamDef as HubLLMDefinition;
55
- }
56
-
57
- throw new Error(`Model provider definition for "${providerName}" not found in hub/llm/${providerName}.json`);
58
- }
59
- }
package/src/llm/llm.ts DELETED
@@ -1,60 +0,0 @@
1
- import { normalizeModelConfig } from "./config";
2
- import { SarvamClient, type SarvamMessage, type SarvamChatResponse } from "./sarvam";
3
- import type { ModelConfig } from "../engine/types";
4
-
5
- export interface LLMMessage {
6
- role: "system" | "user" | "assistant";
7
- content: string;
8
- }
9
-
10
- export interface LLMExecutionResult {
11
- text: string;
12
- reasoningContent?: string;
13
- provider: string;
14
- model: string;
15
- durationMs: number;
16
- usage?: {
17
- promptTokens: number;
18
- completionTokens: number;
19
- totalTokens: number;
20
- };
21
- }
22
-
23
- export class LLMRouter {
24
- private sarvamClient: SarvamClient;
25
-
26
- constructor(private customApiKey?: string) {
27
- this.sarvamClient = new SarvamClient(customApiKey);
28
- }
29
-
30
- public async complete(
31
- modelInput: string | ModelConfig,
32
- messages: LLMMessage[],
33
- environment?: Record<string, string>
34
- ): Promise<LLMExecutionResult> {
35
- const start = performance.now();
36
- const normalized = normalizeModelConfig(modelInput);
37
- const apiKey = environment?.SARVAM_API_KEY || this.customApiKey || process.env.SARVAM_API_KEY;
38
-
39
- if (normalized.provider === "sarvam") {
40
- const response: SarvamChatResponse = await this.sarvamClient.chat(messages as SarvamMessage[], {
41
- model: normalized.model,
42
- temperature: normalized.temperature,
43
- maxTokens: normalized.maxTokens,
44
- apiKey,
45
- endpoint: normalized.endpoint
46
- });
47
-
48
- return {
49
- text: response.text,
50
- reasoningContent: response.reasoningContent,
51
- provider: "sarvam",
52
- model: response.model,
53
- durationMs: performance.now() - start,
54
- usage: response.usage
55
- };
56
- }
57
-
58
- throw new Error(`Provider "${normalized.provider}" is queued for community PR integration.`);
59
- }
60
- }
package/src/llm/sarvam.ts DELETED
@@ -1,136 +0,0 @@
1
- import { HubResolver, type HubLLMDefinition } from "./hub";
2
- import type { ToolCall } from "../agent/types";
3
-
4
- export interface SarvamMessage {
5
- role: "system" | "user" | "assistant" | "tool";
6
- content: string | null;
7
- name?: string;
8
- tool_call_id?: string;
9
- tool_calls?: any[];
10
- }
11
-
12
- export interface SarvamChatOptions {
13
- model?: string;
14
- temperature?: number;
15
- maxTokens?: number;
16
- reasoningEffort?: "none" | "low" | "high" | "max";
17
- apiKey?: string;
18
- endpoint?: string;
19
- tools?: any[];
20
- toolChoice?: string | object;
21
- }
22
-
23
- export interface SarvamChatResponse {
24
- text: string;
25
- reasoningContent?: string;
26
- toolCalls?: ToolCall[];
27
- model: string;
28
- usage?: {
29
- promptTokens: number;
30
- completionTokens: number;
31
- totalTokens: number;
32
- };
33
- }
34
-
35
- export class SarvamClient {
36
- private hubDef: HubLLMDefinition;
37
-
38
- constructor(private apiKey?: string) {
39
- this.hubDef = HubResolver.loadLLM("sarvam");
40
- }
41
-
42
- public async chat(messages: SarvamMessage[], options?: SarvamChatOptions): Promise<SarvamChatResponse> {
43
- const key = options?.apiKey || this.apiKey || process.env.SARVAM_API_KEY;
44
- if (!key) {
45
- throw new Error("Missing SARVAM_API_KEY. Please provide it via options or environment variable.");
46
- }
47
-
48
- let model = options?.model || this.hubDef.default_model;
49
- if (model.includes("/")) {
50
- model = model.split("/").pop() || model;
51
- }
52
- const url = options?.endpoint || this.hubDef.endpoint;
53
-
54
- const payload: Record<string, any> = {
55
- model,
56
- messages: messages.map(m => {
57
- const item: Record<string, any> = {
58
- role: m.role,
59
- content: m.content
60
- };
61
- if (m.name) item.name = m.name;
62
- if (m.tool_call_id) item.tool_call_id = m.tool_call_id;
63
- if (m.tool_calls) item.tool_calls = m.tool_calls;
64
- return item;
65
- }),
66
- temperature: options?.temperature ?? 0.2,
67
- max_tokens: options?.maxTokens ?? 2048
68
- };
69
-
70
- if (options?.tools && options.tools.length > 0) {
71
- payload.tools = options.tools;
72
- if (options.toolChoice) {
73
- payload.tool_choice = options.toolChoice;
74
- }
75
- }
76
-
77
- if (options?.reasoningEffort) {
78
- payload.reasoning_effort = options.reasoningEffort;
79
- }
80
-
81
- const response = await fetch(url, {
82
- method: "POST",
83
- headers: {
84
- "Content-Type": "application/json",
85
- "api-subscription-key": key,
86
- "Authorization": `Bearer ${key}`
87
- },
88
- body: JSON.stringify(payload)
89
- });
90
-
91
- if (!response.ok) {
92
- const errText = await response.text();
93
- throw new Error(`Sarvam API /v2 error (${response.status}): ${errText}`);
94
- }
95
-
96
- const data: any = await response.json();
97
- const choice = data.choices?.[0];
98
- const message = choice?.message || {};
99
-
100
- const rawToolCalls = message.tool_calls;
101
- let toolCalls: ToolCall[] | undefined = undefined;
102
-
103
- if (Array.isArray(rawToolCalls) && rawToolCalls.length > 0) {
104
- toolCalls = rawToolCalls.map((tc: any) => {
105
- let parsedArgs: Record<string, any> = {};
106
- if (typeof tc.function?.arguments === "string") {
107
- try {
108
- parsedArgs = JSON.parse(tc.function.arguments);
109
- } catch {
110
- parsedArgs = { raw: tc.function.arguments };
111
- }
112
- } else if (typeof tc.function?.arguments === "object") {
113
- parsedArgs = tc.function.arguments;
114
- }
115
-
116
- return {
117
- id: tc.id || `call_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
118
- name: tc.function?.name || tc.name,
119
- arguments: parsedArgs
120
- };
121
- });
122
- }
123
-
124
- return {
125
- text: message.content || "",
126
- reasoningContent: message.reasoning_content || message.reasoning || undefined,
127
- toolCalls,
128
- model: data.model || model,
129
- usage: {
130
- promptTokens: data.usage?.prompt_tokens || 0,
131
- completionTokens: data.usage?.completion_tokens || 0,
132
- totalTokens: data.usage?.total_tokens || 0
133
- }
134
- };
135
- }
136
- }
@@ -1,277 +0,0 @@
1
- import { Hono } from "hono";
2
- import { cors } from "hono/cors";
3
- import path from "path";
4
- import fs from "fs";
5
- import { Agent } from "../agent/agent";
6
- import { EnvironmentResolver } from "../environment/environment";
7
- import { LiateMcp } from "../tools/mcp";
8
- import type { MemoryProvider } from "../integration/types";
9
- import { InMemorySession } from "../integration/memory";
10
-
11
- const globalSessionStore = new Map<string, MemoryProvider>();
12
-
13
- export interface EngineServerOptions {
14
- port?: number;
15
- host?: string;
16
- }
17
-
18
- export function createEngineApp() {
19
- const app = new Hono();
20
-
21
- // Enable CORS so any frontend (React, Next.js, mobile app) can call the engine
22
- app.use("*", cors());
23
-
24
- // Health and engine information
25
- app.get("/health", (c) => {
26
- return c.json({
27
- status: "ok",
28
- engine: "openliate",
29
- protocol: "LAPI/v1",
30
- doctrine: "Class is an Agent. Agent is a Function. Function is an API. OpenLiate is Your Backend.",
31
- uptime: process.uptime(),
32
- timestamp: new Date().toISOString()
33
- });
34
- });
35
-
36
- app.get("/", (c) => {
37
- return c.json({
38
- name: "OpenLiate",
39
- status: "running",
40
- endpoints: {
41
- health: "GET /health",
42
- agents: "GET /agents",
43
- run: "POST /run"
44
- }
45
- });
46
- });
47
-
48
- // List available agents in Liate Hub
49
- app.get("/agents", (c) => {
50
- const candidateHubDirs = [
51
- path.resolve(process.cwd(), "hub", "agents"),
52
- path.resolve(process.cwd(), "liate", "hub", "agents"),
53
- path.resolve(__dirname, "../../hub/agents")
54
- ];
55
- const hubDir = candidateHubDirs.find((d) => fs.existsSync(d)) || candidateHubDirs[0];
56
- const agents: Array<{ id: string; name?: string; intent?: string; model?: string }> = [];
57
-
58
- if (fs.existsSync(hubDir)) {
59
- const dirs = fs.readdirSync(hubDir, { withFileTypes: true });
60
- for (const d of dirs) {
61
- if (d.isDirectory()) {
62
- const manifestPath = path.join(hubDir, d.name, "agent.json");
63
- if (fs.existsSync(manifestPath)) {
64
- try {
65
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
66
- agents.push({
67
- id: d.name,
68
- name: manifest.A?.name || manifest.name || d.name,
69
- intent: manifest.A?.intent || manifest.intent || "",
70
- model: typeof manifest.L === "string" ? manifest.L : (manifest.L?.model || manifest.L?.provider || "")
71
- });
72
- } catch {
73
- // Ignore corrupt manifests
74
- }
75
- }
76
- }
77
- }
78
- }
79
-
80
- return c.json({ agents });
81
- });
82
-
83
- // Run any AI agent on the fly (Dynamic ReAct Loop Execution)
84
- app.post("/run", async (c) => {
85
- let body: any = {};
86
- try {
87
- body = await c.req.json();
88
- } catch {
89
- return c.json({ error: "Invalid JSON payload" }, 400);
90
- }
91
-
92
- const prompt = body.prompt;
93
- if (!prompt || typeof prompt !== "string") {
94
- return c.json({ error: "Missing required field 'prompt' (string)" }, 400);
95
- }
96
-
97
- // 1. Resolve on-the-fly API keys and environment variables generically
98
- const onTheFlyKeys: Record<string, string> = {
99
- ...(body.keys || {}),
100
- ...(body.env || {}),
101
- ...(body.agent?.E || {})
102
- };
103
-
104
- // Forward any custom request headers generically (e.g., x-api-key, x-sarvam-api-key, etc.)
105
- const reqHeaders = c.req.header();
106
- for (const [headerName, headerVal] of Object.entries(reqHeaders)) {
107
- if (headerName.startsWith("x-") && headerVal && typeof headerVal === "string") {
108
- const envKey = headerName.slice(2).replace(/-/g, "_").toUpperCase();
109
- onTheFlyKeys[envKey] = headerVal;
110
- }
111
- }
112
-
113
- const previousEnv: Record<string, string | undefined> = {};
114
- for (const [k, v] of Object.entries(onTheFlyKeys)) {
115
- if (typeof v === "string" && v) {
116
- previousEnv[k] = process.env[k];
117
- process.env[k] = v;
118
- }
119
- }
120
-
121
- // 2. Resolve Agent Manifest (On-The-Fly Object or Path)
122
- let manifestPath: string | null = null;
123
- let inlineManifest: any = null;
124
-
125
- if (body.agent && typeof body.agent === "object") {
126
- inlineManifest = body.agent;
127
- } else if (body.manifest && typeof body.manifest === "object") {
128
- inlineManifest = body.manifest;
129
- } else if (body.L) {
130
- inlineManifest = body;
131
- } else if (typeof body.agent === "string") {
132
- const candidates = [
133
- path.resolve(process.cwd(), body.agent),
134
- path.resolve(process.cwd(), "hub", "agents", body.agent, "agent.json"),
135
- path.resolve(process.cwd(), "hub", "agents", body.agent),
136
- path.resolve(process.cwd(), "liate", "hub", "agents", body.agent, "agent.json"),
137
- path.resolve(process.cwd(), "liate", "hub", "agents", body.agent),
138
- path.resolve(__dirname, "..", "..", "hub", "agents", body.agent, "agent.json"),
139
- path.resolve(process.cwd(), "agent.json")
140
- ];
141
-
142
- for (const p of candidates) {
143
- if (fs.existsSync(p)) {
144
- const stat = fs.statSync(p);
145
- if (stat.isFile()) {
146
- manifestPath = p;
147
- break;
148
- }
149
- if (stat.isDirectory()) {
150
- const sub = path.join(p, "agent.json");
151
- if (fs.existsSync(sub)) {
152
- manifestPath = sub;
153
- break;
154
- }
155
- }
156
- }
157
- }
158
- }
159
-
160
- if (!manifestPath && !inlineManifest) {
161
- return c.json(
162
- {
163
- error: "Missing agent definition. Provide an on-the-fly agent object (L·I·A·T·E) or valid agent path."
164
- },
165
- 400
166
- );
167
- }
168
-
169
- // 3. Resolve Session / Memory
170
- const sessionId =
171
- body.sessionId ||
172
- body.session ||
173
- inlineManifest?.I?.sessionId ||
174
- inlineManifest?.I?.session;
175
-
176
- let sessionMemory: MemoryProvider | undefined;
177
- if (sessionId) {
178
- if (!globalSessionStore.has(sessionId)) {
179
- globalSessionStore.set(sessionId, new InMemorySession(sessionId));
180
- }
181
- sessionMemory = globalSessionStore.get(sessionId);
182
- }
183
-
184
- // Pre-seed conversation history if supplied
185
- if (sessionMemory && Array.isArray(body.messages) && body.messages.length > 0) {
186
- const existing = sessionMemory.getMessages();
187
- if (existing.length === 0) {
188
- for (const m of body.messages) {
189
- await sessionMemory.append({
190
- role: m.role || "user",
191
- content: m.content || "",
192
- timestamp: m.timestamp || Date.now()
193
- });
194
- }
195
- }
196
- }
197
-
198
- // 4. Load environment & execute
199
- if (manifestPath) {
200
- EnvironmentResolver.loadEnv(manifestPath);
201
- }
202
-
203
- const t0 = Date.now();
204
- try {
205
- const agent = inlineManifest
206
- ? new Agent({ manifest: inlineManifest, memory: sessionMemory })
207
- : new Agent({ manifest: manifestPath!, memory: sessionMemory });
208
-
209
- const result = await agent.run(prompt);
210
- const latencyMs = Date.now() - t0;
211
-
212
- return c.json({
213
- success: true,
214
- agent: agent.name,
215
- sessionId: agent.getMemory().sessionId,
216
- prompt,
217
- text: result.text.trim(),
218
- thought: result.thought || null,
219
- model: result.model,
220
- totalSteps: result.totalSteps,
221
- latencyMs,
222
- protocol: "LAPI/v1"
223
- });
224
- } catch (err: any) {
225
- return c.json(
226
- {
227
- success: false,
228
- error: err.message || "Agent execution failed",
229
- latencyMs: Date.now() - t0
230
- },
231
- 500
232
- );
233
- } finally {
234
- // Restore environment state to avoid bleeding ephemeral keys
235
- for (const [k, prevVal] of Object.entries(previousEnv)) {
236
- if (prevVal !== undefined) {
237
- process.env[k] = prevVal;
238
- } else {
239
- delete process.env[k];
240
- }
241
- }
242
- await LiateMcp.closeAll();
243
- }
244
- });
245
-
246
- return app;
247
- }
248
-
249
- export function startEngineServer(options?: EngineServerOptions) {
250
- const port = options?.port || 3000;
251
- const host = options?.host || "0.0.0.0";
252
- const app = createEngineApp();
253
-
254
- console.log(`[Liate] Starting Pure Engine Server on port ${port}...`);
255
- console.log(`[Liate] Doctrine: "Class is an Agent. Agent is a Function. Function is an API."`);
256
-
257
- // Native Bun / Node server
258
- const server = (globalThis as any).Bun?.serve
259
- ? (globalThis as any).Bun.serve({
260
- fetch: app.fetch,
261
- port,
262
- hostname: host
263
- })
264
- : null;
265
-
266
- return {
267
- app,
268
- server,
269
- port,
270
- close: () => {
271
- if (server?.stop) {
272
- server.stop();
273
- }
274
- }
275
- };
276
- }
277
-
@@ -1,32 +0,0 @@
1
- import { createEngineApp } from "./engine";
2
- import { serve } from "@hono/node-server";
3
-
4
- const app = createEngineApp();
5
-
6
- const port = parseInt(process.env.PORT || "3000", 10);
7
- const host = process.env.HOST || "0.0.0.0";
8
-
9
- // When run in Deno (Supabase Edge Functions)
10
- if (typeof (globalThis as any).Deno !== "undefined" && typeof (globalThis as any).Deno.serve === "function") {
11
- (globalThis as any).Deno.serve((req: Request) => app.fetch(req));
12
- } else if (typeof process !== "undefined" && process.env.NODE_ENV !== "test") {
13
- if ((globalThis as any).Bun?.serve) {
14
- (globalThis as any).Bun.serve({
15
- fetch: app.fetch,
16
- port,
17
- hostname: host
18
- });
19
- console.log(`[Liate] Engine running on Bun (http://${host}:${port})`);
20
- } else {
21
- try {
22
- serve({
23
- fetch: app.fetch,
24
- port,
25
- hostname: host
26
- });
27
- console.log(`[Liate] Engine running on Node.js (http://${host}:${port})`);
28
- } catch {}
29
- }
30
- }
31
-
32
- export default app;
@@ -1,66 +0,0 @@
1
- import type { AgentTool } from "../../agent/types";
2
-
3
- export const fetchTool: AgentTool = {
4
- name: "fetch",
5
- description: "Make an HTTP request (GET, POST, PUT, DELETE) to an external URL or API endpoint.",
6
- parameters: {
7
- type: "object",
8
- properties: {
9
- url: {
10
- type: "string",
11
- description: "The complete HTTP or HTTPS URL to fetch"
12
- },
13
- method: {
14
- type: "string",
15
- enum: ["GET", "POST", "PUT", "DELETE", "PATCH"],
16
- description: "HTTP method to use (defaults to GET)"
17
- },
18
- headers: {
19
- type: "object",
20
- description: "Key-value pairs of request headers"
21
- },
22
- body: {
23
- type: "string",
24
- description: "Request body string (for POST/PUT requests)"
25
- }
26
- },
27
- required: ["url"]
28
- },
29
- execute: async (args: Record<string, any>) => {
30
- const url = args.url;
31
- if (!url || typeof url !== "string") {
32
- throw new Error("Missing or invalid 'url' parameter for fetch tool");
33
- }
34
-
35
- const method = (args.method || "GET").toUpperCase();
36
- const headers: Record<string, string> = args.headers || {};
37
- const fetchOptions: RequestInit = {
38
- method,
39
- headers
40
- };
41
-
42
- if (args.body && (method === "POST" || method === "PUT" || method === "PATCH")) {
43
- fetchOptions.body = typeof args.body === "string" ? args.body : JSON.stringify(args.body);
44
- if (!headers["Content-Type"]) {
45
- headers["Content-Type"] = "application/json";
46
- }
47
- }
48
-
49
- try {
50
- const response = await fetch(url, fetchOptions);
51
- const contentType = response.headers.get("content-type") || "";
52
-
53
- let bodyText: string;
54
- if (contentType.includes("application/json")) {
55
- const json = await response.json();
56
- bodyText = JSON.stringify(json, null, 2);
57
- } else {
58
- bodyText = await response.text();
59
- }
60
-
61
- return `Status: ${response.status} ${response.statusText}\nBody:\n${bodyText.slice(0, 4000)}`;
62
- } catch (err: any) {
63
- return `HTTP Request failed for ${url}: ${err.message}`;
64
- }
65
- }
66
- };