research-powerpack-mcp 3.4.8 → 3.5.0
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/README.md +63 -674
- package/dist/clients/reddit.d.ts +1 -6
- package/dist/clients/reddit.d.ts.map +1 -1
- package/dist/clients/reddit.js +24 -60
- package/dist/clients/reddit.js.map +1 -1
- package/dist/clients/scraper.d.ts +1 -6
- package/dist/clients/scraper.d.ts.map +1 -1
- package/dist/clients/scraper.js +33 -71
- package/dist/clients/scraper.js.map +1 -1
- package/dist/clients/search.d.ts +2 -2
- package/dist/clients/search.d.ts.map +1 -1
- package/dist/clients/search.js +6 -11
- package/dist/clients/search.js.map +1 -1
- package/dist/config/env.d.ts +75 -0
- package/dist/config/env.d.ts.map +1 -0
- package/dist/config/env.js +87 -0
- package/dist/config/env.js.map +1 -0
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +1 -5
- package/dist/config/index.js.map +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +1 -6
- package/dist/config/loader.js.map +1 -1
- package/dist/config/yaml/tools-enhanced.yaml +0 -0
- package/dist/index.js +85 -25
- package/dist/index.js.map +1 -1
- package/dist/schemas/web-search.js +1 -1
- package/dist/schemas/web-search.js.map +1 -1
- package/dist/services/file-attachment.d.ts.map +1 -1
- package/dist/services/file-attachment.js +22 -25
- package/dist/services/file-attachment.js.map +1 -1
- package/dist/services/llm-processor.js +0 -25
- package/dist/services/llm-processor.js.map +1 -1
- package/dist/tools/reddit.d.ts.map +1 -1
- package/dist/tools/reddit.js +77 -29
- package/dist/tools/reddit.js.map +1 -1
- package/dist/tools/registry.js +2 -2
- package/dist/tools/registry.js.map +1 -1
- package/dist/tools/research.d.ts +2 -6
- package/dist/tools/research.d.ts.map +1 -1
- package/dist/tools/research.js +64 -53
- package/dist/tools/research.js.map +1 -1
- package/dist/tools/scrape.d.ts +1 -5
- package/dist/tools/scrape.d.ts.map +1 -1
- package/dist/tools/scrape.js +108 -66
- package/dist/tools/scrape.js.map +1 -1
- package/dist/tools/search.d.ts +1 -5
- package/dist/tools/search.d.ts.map +1 -1
- package/dist/tools/search.js +26 -16
- package/dist/tools/search.js.map +1 -1
- package/dist/tools/utils.d.ts +20 -59
- package/dist/tools/utils.d.ts.map +1 -1
- package/dist/tools/utils.js +25 -61
- package/dist/tools/utils.js.map +1 -1
- package/dist/utils/logger.d.ts +36 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +40 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/response.d.ts +101 -0
- package/dist/utils/response.d.ts.map +1 -0
- package/dist/utils/response.js +183 -0
- package/dist/utils/response.js.map +1 -0
- package/dist/utils/url-aggregator.d.ts.map +1 -1
- package/dist/utils/url-aggregator.js +4 -6
- package/dist/utils/url-aggregator.js.map +1 -1
- package/package.json +8 -2
- package/dist/utils/concurrency.d.ts +0 -29
- package/dist/utils/concurrency.d.ts.map +0 -1
- package/dist/utils/concurrency.js +0 -73
- package/dist/utils/concurrency.js.map +0 -1
package/dist/tools/scrape.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Scrape Links Tool Handler
|
|
3
3
|
* Implements robust error handling that NEVER crashes the MCP server
|
|
4
4
|
*/
|
|
5
|
+
import pLimit from 'p-limit';
|
|
5
6
|
import { ScraperClient } from '../clients/scraper.js';
|
|
6
7
|
import { MarkdownCleaner } from '../services/markdown-cleaner.js';
|
|
7
8
|
import { createLLMProcessor, processContentWithLLM } from '../services/llm-processor.js';
|
|
@@ -9,36 +10,16 @@ import { removeMetaTags } from '../utils/markdown-formatter.js';
|
|
|
9
10
|
import { SCRAPER } from '../config/index.js';
|
|
10
11
|
import { getToolConfig } from '../config/loader.js';
|
|
11
12
|
import { classifyError } from '../utils/errors.js';
|
|
12
|
-
|
|
13
|
-
const markdownCleaner = new MarkdownCleaner();
|
|
13
|
+
import { safeLog, calculateTokenAllocation, TOKEN_BUDGETS, formatSuccess, formatError, formatBatchHeader, formatDuration, } from './utils.js';
|
|
14
14
|
// Get extraction suffix from YAML config (fallback to hardcoded if not found)
|
|
15
15
|
function getExtractionSuffix() {
|
|
16
16
|
const config = getToolConfig('scrape_links');
|
|
17
17
|
return config?.limits?.extraction_suffix || SCRAPER.EXTRACTION_SUFFIX;
|
|
18
18
|
}
|
|
19
|
-
function calculateTokenAllocation(urlCount) {
|
|
20
|
-
if (urlCount <= 0)
|
|
21
|
-
return SCRAPER.MAX_TOKENS_BUDGET;
|
|
22
|
-
return Math.floor(SCRAPER.MAX_TOKENS_BUDGET / urlCount);
|
|
23
|
-
}
|
|
24
19
|
function enhanceExtractionInstruction(instruction) {
|
|
25
20
|
const base = instruction || 'Extract the main content and key information from this page.';
|
|
26
21
|
return `${base}\n\n${getExtractionSuffix()}`;
|
|
27
22
|
}
|
|
28
|
-
/**
|
|
29
|
-
* Safe logger wrapper - NEVER throws
|
|
30
|
-
*/
|
|
31
|
-
async function safeLog(logger, sessionId, level, message) {
|
|
32
|
-
if (!logger || !sessionId)
|
|
33
|
-
return;
|
|
34
|
-
try {
|
|
35
|
-
await logger(level, message, sessionId);
|
|
36
|
-
}
|
|
37
|
-
catch {
|
|
38
|
-
// Silently ignore logger errors - they should never crash the tool
|
|
39
|
-
console.error(`[Scrape Tool] Logger failed: ${message}`);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
23
|
/**
|
|
43
24
|
* Handle scrape links request
|
|
44
25
|
* NEVER throws - always returns a valid response with content and metadata
|
|
@@ -46,23 +27,32 @@ async function safeLog(logger, sessionId, level, message) {
|
|
|
46
27
|
export async function handleScrapeLinks(params, options = {}) {
|
|
47
28
|
const { sessionId, logger } = options;
|
|
48
29
|
const startTime = Date.now();
|
|
49
|
-
// Helper to create error response
|
|
50
|
-
const createErrorResponse = (message,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
30
|
+
// Helper to create error response using standardized formatter
|
|
31
|
+
const createErrorResponse = (message, code = 'SCRAPE_ERROR') => {
|
|
32
|
+
const executionTime = Date.now() - startTime;
|
|
33
|
+
const errorContent = formatError({
|
|
34
|
+
code,
|
|
35
|
+
message,
|
|
36
|
+
retryable: false,
|
|
37
|
+
toolName: 'Scrape Links',
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
content: errorContent,
|
|
41
|
+
structuredContent: {
|
|
42
|
+
content: errorContent,
|
|
43
|
+
metadata: {
|
|
44
|
+
total_urls: params.urls?.length || 0,
|
|
45
|
+
successful: 0,
|
|
46
|
+
failed: params.urls?.length || 0,
|
|
47
|
+
total_credits: 0,
|
|
48
|
+
execution_time_ms: executionTime,
|
|
49
|
+
},
|
|
60
50
|
},
|
|
61
|
-
}
|
|
62
|
-
}
|
|
51
|
+
};
|
|
52
|
+
};
|
|
63
53
|
// Validate params
|
|
64
54
|
if (!params.urls || params.urls.length === 0) {
|
|
65
|
-
return createErrorResponse('No URLs provided',
|
|
55
|
+
return createErrorResponse('No URLs provided', 'INVALID_INPUT');
|
|
66
56
|
}
|
|
67
57
|
// Filter out invalid URLs early
|
|
68
58
|
const validUrls = [];
|
|
@@ -77,11 +67,11 @@ export async function handleScrapeLinks(params, options = {}) {
|
|
|
77
67
|
}
|
|
78
68
|
}
|
|
79
69
|
if (validUrls.length === 0) {
|
|
80
|
-
return createErrorResponse(`All ${params.urls.length} URLs are invalid`,
|
|
70
|
+
return createErrorResponse(`All ${params.urls.length} URLs are invalid`, 'INVALID_INPUT');
|
|
81
71
|
}
|
|
82
|
-
const tokensPerUrl = calculateTokenAllocation(validUrls.length);
|
|
72
|
+
const tokensPerUrl = calculateTokenAllocation(validUrls.length, TOKEN_BUDGETS.SCRAPER);
|
|
83
73
|
const totalBatches = Math.ceil(validUrls.length / SCRAPER.BATCH_SIZE);
|
|
84
|
-
await safeLog(logger, sessionId, 'info', `Starting scrape: ${validUrls.length} URL(s), ${tokensPerUrl} tokens/URL, ${totalBatches} batch(es)
|
|
74
|
+
await safeLog(logger, sessionId, 'info', `Starting scrape: ${validUrls.length} URL(s), ${tokensPerUrl} tokens/URL, ${totalBatches} batch(es)`, 'Scrape');
|
|
85
75
|
// Initialize clients safely
|
|
86
76
|
let client;
|
|
87
77
|
try {
|
|
@@ -89,15 +79,16 @@ export async function handleScrapeLinks(params, options = {}) {
|
|
|
89
79
|
}
|
|
90
80
|
catch (error) {
|
|
91
81
|
const err = classifyError(error);
|
|
92
|
-
return createErrorResponse(`Failed to initialize scraper: ${err.message}`,
|
|
82
|
+
return createErrorResponse(`Failed to initialize scraper: ${err.message}`, 'INIT_ERROR');
|
|
93
83
|
}
|
|
84
|
+
const markdownCleaner = new MarkdownCleaner();
|
|
94
85
|
const llmProcessor = createLLMProcessor(); // Returns null if not configured
|
|
95
86
|
const enhancedInstruction = params.use_llm
|
|
96
87
|
? enhanceExtractionInstruction(params.what_to_extract)
|
|
97
88
|
: undefined;
|
|
98
89
|
// Scrape URLs - scrapeMultiple NEVER throws
|
|
99
90
|
const results = await client.scrapeMultiple(validUrls, { timeout: params.timeout });
|
|
100
|
-
await safeLog(logger, sessionId, 'info', `Scraping complete. Processing ${results.length} results
|
|
91
|
+
await safeLog(logger, sessionId, 'info', `Scraping complete. Processing ${results.length} results...`, 'Scrape');
|
|
101
92
|
let successful = 0;
|
|
102
93
|
let failed = 0;
|
|
103
94
|
let totalCredits = 0;
|
|
@@ -108,7 +99,7 @@ export async function handleScrapeLinks(params, options = {}) {
|
|
|
108
99
|
failed++;
|
|
109
100
|
contents.push(`## ${invalidUrl}\n\n❌ Invalid URL format`);
|
|
110
101
|
}
|
|
111
|
-
|
|
102
|
+
const processed = [];
|
|
112
103
|
for (let i = 0; i < results.length; i++) {
|
|
113
104
|
const result = results[i];
|
|
114
105
|
if (!result) {
|
|
@@ -116,13 +107,11 @@ export async function handleScrapeLinks(params, options = {}) {
|
|
|
116
107
|
contents.push(`## Unknown URL\n\n❌ No result returned`);
|
|
117
108
|
continue;
|
|
118
109
|
}
|
|
119
|
-
await safeLog(logger, sessionId, 'info', `[${i + 1}/${results.length}] Processing ${result.url}`);
|
|
120
110
|
// Check for errors in result
|
|
121
111
|
if (result.error || result.statusCode < 200 || result.statusCode >= 300) {
|
|
122
112
|
failed++;
|
|
123
113
|
const errorMsg = result.error?.message || result.content || `HTTP ${result.statusCode}`;
|
|
124
114
|
contents.push(`## ${result.url}\n\n❌ Failed to scrape: ${errorMsg}`);
|
|
125
|
-
await safeLog(logger, sessionId, 'error', `[${i + 1}/${results.length}] Failed: ${errorMsg}`);
|
|
126
115
|
continue;
|
|
127
116
|
}
|
|
128
117
|
// Success case
|
|
@@ -134,38 +123,91 @@ export async function handleScrapeLinks(params, options = {}) {
|
|
|
134
123
|
content = markdownCleaner.processContent(result.content);
|
|
135
124
|
}
|
|
136
125
|
catch {
|
|
137
|
-
// If markdown cleaning fails, use raw content
|
|
138
126
|
content = result.content;
|
|
139
127
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
128
|
+
processed.push({ url: result.url, content, isSuccess: true, index: i });
|
|
129
|
+
}
|
|
130
|
+
// Second pass: parallel LLM extraction for successful results
|
|
131
|
+
if (params.use_llm && llmProcessor && processed.length > 0) {
|
|
132
|
+
await safeLog(logger, sessionId, 'info', `Applying LLM extraction to ${processed.length} results (concurrency: 3)...`, 'Scrape');
|
|
133
|
+
const llmLimit = pLimit(3);
|
|
134
|
+
const llmResults = await Promise.allSettled(processed.map(p => llmLimit(async () => {
|
|
135
|
+
const llmResult = await processContentWithLLM(p.content, { use_llm: params.use_llm, what_to_extract: enhancedInstruction, max_tokens: tokensPerUrl }, llmProcessor);
|
|
136
|
+
return { ...p, llmResult };
|
|
137
|
+
})));
|
|
138
|
+
for (const entry of llmResults) {
|
|
139
|
+
if (entry.status === 'fulfilled') {
|
|
140
|
+
const { url, llmResult } = entry.value;
|
|
141
|
+
let content = entry.value.content;
|
|
142
|
+
if (llmResult.processed) {
|
|
143
|
+
content = llmResult.content;
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
llmErrors++;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
content = removeMetaTags(content);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
// If this fails, just use the content as-is
|
|
153
|
+
}
|
|
154
|
+
contents.push(`## ${url}\n\n${content}`);
|
|
147
155
|
}
|
|
148
156
|
else {
|
|
157
|
+
// Safety net — processContentWithLLM never throws, but handle anyway
|
|
149
158
|
llmErrors++;
|
|
150
|
-
|
|
151
|
-
|
|
159
|
+
// We can't easily recover the URL here, so this is a rare edge case
|
|
160
|
+
contents.push(`## Unknown URL\n\n❌ LLM processing failed unexpectedly`);
|
|
152
161
|
}
|
|
153
162
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
// No LLM — just finalize each successful result
|
|
166
|
+
for (const p of processed) {
|
|
167
|
+
let content = p.content;
|
|
168
|
+
try {
|
|
169
|
+
content = removeMetaTags(content);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// If this fails, just use the content as-is
|
|
173
|
+
}
|
|
174
|
+
contents.push(`## ${p.url}\n\n${content}`);
|
|
160
175
|
}
|
|
161
|
-
contents.push(`## ${result.url}\n\n${content}`);
|
|
162
176
|
}
|
|
163
177
|
const executionTime = Date.now() - startTime;
|
|
164
|
-
await safeLog(logger, sessionId, 'info', `Completed: ${successful} successful, ${failed} failed, ${totalCredits} credits used
|
|
165
|
-
// Build response
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
178
|
+
await safeLog(logger, sessionId, 'info', `Completed: ${successful} successful, ${failed} failed, ${totalCredits} credits used`, 'Scrape');
|
|
179
|
+
// Build response using standardized formatters
|
|
180
|
+
const headerInfo = formatBatchHeader({
|
|
181
|
+
title: 'Scraped Content',
|
|
182
|
+
totalItems: params.urls.length,
|
|
183
|
+
successful,
|
|
184
|
+
failed,
|
|
185
|
+
tokensPerItem: tokensPerUrl,
|
|
186
|
+
totalBudget: TOKEN_BUDGETS.SCRAPER,
|
|
187
|
+
batches: totalBatches,
|
|
188
|
+
extras: llmErrors > 0 ? [`⚠️ ${llmErrors} LLM extraction failures`] : undefined,
|
|
189
|
+
});
|
|
190
|
+
// Build next steps based on results
|
|
191
|
+
const nextSteps = [];
|
|
192
|
+
if (successful > 0) {
|
|
193
|
+
nextSteps.push('Use `deep_research()` for in-depth analysis of specific topics found');
|
|
194
|
+
nextSteps.push('Run `web_search()` to find related content');
|
|
195
|
+
}
|
|
196
|
+
if (failed > 0) {
|
|
197
|
+
nextSteps.push(`Retry failed URLs with increased timeout: \`scrape_links({urls: [...], timeout: 60})\``);
|
|
198
|
+
}
|
|
199
|
+
const formattedContent = formatSuccess({
|
|
200
|
+
title: `Scraped Content (${params.urls.length} URLs)`,
|
|
201
|
+
summary: `${headerInfo}\n\n**Execution Time:** ${formatDuration(executionTime)} | **Credits Used:** ${totalCredits}`,
|
|
202
|
+
data: contents.join('\n\n---\n\n'),
|
|
203
|
+
nextSteps,
|
|
204
|
+
metadata: {
|
|
205
|
+
'Total URLs': params.urls.length,
|
|
206
|
+
'Successful': successful,
|
|
207
|
+
'Failed': failed,
|
|
208
|
+
'Tokens/URL': tokensPerUrl,
|
|
209
|
+
},
|
|
210
|
+
});
|
|
169
211
|
const metadata = {
|
|
170
212
|
total_urls: params.urls.length,
|
|
171
213
|
successful,
|
|
@@ -173,7 +215,7 @@ export async function handleScrapeLinks(params, options = {}) {
|
|
|
173
215
|
total_credits: totalCredits,
|
|
174
216
|
execution_time_ms: executionTime,
|
|
175
217
|
tokens_per_url: tokensPerUrl,
|
|
176
|
-
total_token_budget: SCRAPER
|
|
218
|
+
total_token_budget: TOKEN_BUDGETS.SCRAPER,
|
|
177
219
|
batches_processed: totalBatches,
|
|
178
220
|
};
|
|
179
221
|
return { content: formattedContent, structuredContent: { content: formattedContent, metadata } };
|
package/dist/tools/scrape.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scrape.js","sourceRoot":"","sources":["../../src/tools/scrape.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"scrape.js","sourceRoot":"","sources":["../../src/tools/scrape.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,MAAM,MAAM,SAAS,CAAC;AAE7B,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,OAAO,EAEP,wBAAwB,EACxB,aAAa,EACb,aAAa,EACb,WAAW,EACX,iBAAiB,EACjB,cAAc,GACf,MAAM,YAAY,CAAC;AAEpB,8EAA8E;AAC9E,SAAS,mBAAmB;IAC1B,MAAM,MAAM,GAAG,aAAa,CAAC,cAAc,CAAC,CAAC;IAC7C,OAAO,MAAM,EAAE,MAAM,EAAE,iBAA2B,IAAI,OAAO,CAAC,iBAAiB,CAAC;AAClF,CAAC;AAED,SAAS,4BAA4B,CAAC,WAA+B;IACnE,MAAM,IAAI,GAAG,WAAW,IAAI,8DAA8D,CAAC;IAC3F,OAAO,GAAG,IAAI,OAAO,mBAAmB,EAAE,EAAE,CAAC;AAC/C,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,U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C5B,kBAAkB,EAAE,aAAa,CAAC,OAAO;QACzC,iBAAiB,EAAE,YAAY;KAChC,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,EAAE,CAAC;AACnG,CAAC"}
|
package/dist/tools/search.d.ts
CHANGED
|
@@ -3,13 +3,9 @@
|
|
|
3
3
|
* NEVER throws - always returns structured response for graceful degradation
|
|
4
4
|
*/
|
|
5
5
|
import type { WebSearchParams, WebSearchOutput } from '../schemas/web-search.js';
|
|
6
|
-
|
|
7
|
-
sessionId?: string;
|
|
8
|
-
logger?: (level: 'info' | 'error' | 'debug', message: string, sessionId: string) => Promise<void>;
|
|
9
|
-
}
|
|
6
|
+
import { type ToolOptions } from './utils.js';
|
|
10
7
|
export declare function handleWebSearch(params: WebSearchParams, options?: ToolOptions): Promise<{
|
|
11
8
|
content: string;
|
|
12
9
|
structuredContent: WebSearchOutput;
|
|
13
10
|
}>;
|
|
14
|
-
export {};
|
|
15
11
|
//# sourceMappingURL=search.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/tools/search.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/tools/search.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAWjF,OAAO,EAEL,KAAK,WAAW,EAIjB,MAAM,YAAY,CAAC;AASpB,wBAAsB,eAAe,CACnC,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,iBAAiB,EAAE,eAAe,CAAA;CAAE,CAAC,CAgKlE"}
|
package/dist/tools/search.js
CHANGED
|
@@ -6,6 +6,7 @@ import { SearchClient } from '../clients/search.js';
|
|
|
6
6
|
import { aggregateAndRank, buildUrlLookup, lookupUrl, generateEnhancedOutput, markConsensus, } from '../utils/url-aggregator.js';
|
|
7
7
|
import { CTR_WEIGHTS } from '../config/index.js';
|
|
8
8
|
import { classifyError } from '../utils/errors.js';
|
|
9
|
+
import { safeLog, formatSuccess, formatError, formatDuration, } from './utils.js';
|
|
9
10
|
function getPositionScore(position) {
|
|
10
11
|
if (position >= 1 && position <= 10) {
|
|
11
12
|
return CTR_WEIGHTS[position] ?? 0;
|
|
@@ -16,9 +17,7 @@ export async function handleWebSearch(params, options = {}) {
|
|
|
16
17
|
const { sessionId, logger } = options;
|
|
17
18
|
const startTime = Date.now();
|
|
18
19
|
try {
|
|
19
|
-
|
|
20
|
-
await logger('info', `Searching for ${params.keywords.length} keyword(s)`, sessionId);
|
|
21
|
-
}
|
|
20
|
+
await safeLog(logger, sessionId, 'info', `Searching for ${params.keywords.length} keyword(s)`, 'WebSearch');
|
|
22
21
|
const client = new SearchClient();
|
|
23
22
|
const response = await client.searchMultiple(params.keywords);
|
|
24
23
|
const aggregation = aggregateAndRank(response.searches, 5);
|
|
@@ -87,9 +86,19 @@ export async function handleWebSearch(params, options = {}) {
|
|
|
87
86
|
markdown += `\n---\n\n> *${queriesOmitted} additional queries not shown. Consensus URLs above include all ${response.searches.length} queries.*\n`;
|
|
88
87
|
}
|
|
89
88
|
const executionTime = Date.now() - startTime;
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
89
|
+
await safeLog(logger, sessionId, 'info', `Search completed: ${totalResults} results, ${aggregation.totalUniqueUrls} unique URLs, ${consensusUrls.length} consensus URLs in ${executionTime}ms`, 'WebSearch');
|
|
90
|
+
// Add next steps section
|
|
91
|
+
const nextSteps = [
|
|
92
|
+
`Scrape top URLs: \`scrape_links({urls: [${consensusUrls.slice(0, 3).map(u => `"${u.url}"`).join(', ')}], use_llm: true})\``,
|
|
93
|
+
'Use `deep_research()` for in-depth analysis of specific topics',
|
|
94
|
+
'Refine search with more specific keywords based on results',
|
|
95
|
+
];
|
|
96
|
+
const formattedContent = formatSuccess({
|
|
97
|
+
title: `Web Search Results (${params.keywords.length} keywords)`,
|
|
98
|
+
summary: `**Found ${totalResults} results** across ${response.totalKeywords} queries\n• ${aggregation.totalUniqueUrls} unique URLs\n• ${consensusUrls.length} consensus URLs (appeared in ${aggregation.frequencyThreshold}+ searches)\n• Execution time: ${formatDuration(executionTime)}`,
|
|
99
|
+
data: markdown,
|
|
100
|
+
nextSteps,
|
|
101
|
+
});
|
|
93
102
|
const metadata = {
|
|
94
103
|
total_keywords: response.totalKeywords,
|
|
95
104
|
total_results: totalResults,
|
|
@@ -98,20 +107,21 @@ export async function handleWebSearch(params, options = {}) {
|
|
|
98
107
|
consensus_url_count: consensusUrls.length,
|
|
99
108
|
frequency_threshold: aggregation.frequencyThreshold,
|
|
100
109
|
};
|
|
101
|
-
return { content:
|
|
110
|
+
return { content: formattedContent, structuredContent: { content: formattedContent, metadata } };
|
|
102
111
|
}
|
|
103
112
|
catch (error) {
|
|
104
113
|
// Classify error for better reporting
|
|
105
114
|
const structuredError = classifyError(error);
|
|
106
|
-
|
|
107
|
-
if (sessionId && logger) {
|
|
108
|
-
await logger('error', `web_search: ${structuredError.message}`, sessionId);
|
|
109
|
-
}
|
|
115
|
+
await safeLog(logger, sessionId, 'error', `web_search: ${structuredError.message}`, 'WebSearch');
|
|
110
116
|
const executionTime = Date.now() - startTime;
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
:
|
|
114
|
-
|
|
117
|
+
const errorContent = formatError({
|
|
118
|
+
code: structuredError.code,
|
|
119
|
+
message: structuredError.message,
|
|
120
|
+
retryable: structuredError.retryable,
|
|
121
|
+
toolName: 'web_search',
|
|
122
|
+
howToFix: ['Make sure SERPER_API_KEY is set in your environment variables'],
|
|
123
|
+
alternatives: ['Try search_reddit() for community discussions', 'Use deep_research() for AI-powered research'],
|
|
124
|
+
});
|
|
115
125
|
return {
|
|
116
126
|
content: errorContent,
|
|
117
127
|
structuredContent: {
|
|
@@ -120,7 +130,7 @@ export async function handleWebSearch(params, options = {}) {
|
|
|
120
130
|
total_keywords: params.keywords.length,
|
|
121
131
|
total_results: 0,
|
|
122
132
|
execution_time_ms: executionTime,
|
|
123
|
-
errorCode
|
|
133
|
+
errorCode: structuredError.code,
|
|
124
134
|
},
|
|
125
135
|
},
|
|
126
136
|
};
|
package/dist/tools/search.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/tools/search.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,SAAS,EACT,sBAAsB,EACtB,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,aAAa,
|
|
1
|
+
{"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/tools/search.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,SAAS,EACT,sBAAsB,EACtB,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,OAAO,EAEP,aAAa,EACb,WAAW,EACX,cAAc,GACf,MAAM,YAAY,CAAC;AAEpB,SAAS,gBAAgB,CAAC,QAAgB;IACxC,IAAI,QAAQ,IAAI,CAAC,IAAI,QAAQ,IAAI,EAAE,EAAE,CAAC;QACpC,OAAO,WAAW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3
|
-
*
|
|
3
|
+
* Central module for common tool functionality
|
|
4
|
+
* Re-exports from specialized utility modules for backwards compatibility
|
|
4
5
|
*/
|
|
6
|
+
export { safeLog, createToolLogger, type ToolLogger, type ToolOptions } from '../utils/logger.js';
|
|
7
|
+
export { formatSuccess, formatError, formatBatchHeader, formatList, formatKeyValues, formatDuration, truncateText, type SuccessResponseOptions, type ErrorResponseOptions, type BatchResultOptions, } from '../utils/response.js';
|
|
5
8
|
/**
|
|
6
|
-
*
|
|
9
|
+
* Token budgets for different tools
|
|
10
|
+
* Centralized here to ensure consistency
|
|
7
11
|
*/
|
|
8
|
-
export
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Safe logger wrapper - NEVER throws
|
|
18
|
-
* Logs to provided logger or falls back to console.error
|
|
19
|
-
*
|
|
20
|
-
* @param logger - Optional logger function
|
|
21
|
-
* @param sessionId - Session ID for logging context
|
|
22
|
-
* @param level - Log level
|
|
23
|
-
* @param message - Message to log
|
|
24
|
-
* @param toolName - Name of the tool for prefixing
|
|
25
|
-
*/
|
|
26
|
-
export declare function safeLog(logger: ToolLogger | undefined, sessionId: string | undefined, level: 'info' | 'error' | 'debug', message: string, toolName: string): Promise<void>;
|
|
12
|
+
export declare const TOKEN_BUDGETS: {
|
|
13
|
+
/** Total token budget for deep research */
|
|
14
|
+
readonly RESEARCH: 32000;
|
|
15
|
+
/** Total token budget for web scraping */
|
|
16
|
+
readonly SCRAPER: 32000;
|
|
17
|
+
/** Total token budget for Reddit post fetching */
|
|
18
|
+
readonly REDDIT: 1000;
|
|
19
|
+
};
|
|
27
20
|
/**
|
|
28
21
|
* Calculate token allocation for batch operations
|
|
29
22
|
* Distributes a fixed budget across multiple items
|
|
30
23
|
*
|
|
31
24
|
* @param count - Number of items to distribute budget across
|
|
32
|
-
* @param budget - Total token budget
|
|
25
|
+
* @param budget - Total token budget (defaults to RESEARCH budget)
|
|
33
26
|
* @returns Tokens per item
|
|
34
27
|
*/
|
|
35
|
-
export declare function calculateTokenAllocation(count: number, budget
|
|
28
|
+
export declare function calculateTokenAllocation(count: number, budget?: number): number;
|
|
36
29
|
/**
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* @param retryable - Whether the error is retryable
|
|
40
|
-
* @returns Hint string or empty string
|
|
30
|
+
* @deprecated Use formatError from response.ts instead
|
|
41
31
|
*/
|
|
42
32
|
export declare function formatRetryHint(retryable: boolean): string;
|
|
43
33
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
* @param toolName - Name of the tool that errored
|
|
47
|
-
* @param errorCode - Error code
|
|
48
|
-
* @param message - Error message
|
|
49
|
-
* @param retryable - Whether error is retryable
|
|
50
|
-
* @param tip - Optional tip for resolution
|
|
51
|
-
* @returns Formatted markdown error string
|
|
34
|
+
* @deprecated Use formatError from response.ts instead
|
|
52
35
|
*/
|
|
53
36
|
export declare function formatToolError(toolName: string, errorCode: string, message: string, retryable: boolean, tip?: string): string;
|
|
54
37
|
/**
|
|
55
38
|
* Validate that a value is a non-empty array
|
|
56
|
-
*
|
|
57
|
-
* @param value - Value to check
|
|
58
|
-
* @param fieldName - Field name for error message
|
|
59
|
-
* @returns Error message or undefined if valid
|
|
60
39
|
*/
|
|
61
40
|
export declare function validateNonEmptyArray(value: unknown, fieldName: string): string | undefined;
|
|
62
41
|
/**
|
|
63
42
|
* Validate array length is within bounds
|
|
64
|
-
*
|
|
65
|
-
* @param arr - Array to check
|
|
66
|
-
* @param min - Minimum length
|
|
67
|
-
* @param max - Maximum length
|
|
68
|
-
* @param fieldName - Field name for error message
|
|
69
|
-
* @returns Error message or undefined if valid
|
|
70
43
|
*/
|
|
71
44
|
export declare function validateArrayBounds(arr: unknown[], min: number, max: number, fieldName: string): string | undefined;
|
|
72
45
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* @param title - Title of the results section
|
|
76
|
-
* @param count - Number of items processed
|
|
77
|
-
* @param tokensPerItem - Tokens allocated per item
|
|
78
|
-
* @param totalBudget - Total token budget
|
|
79
|
-
* @returns Formatted header string
|
|
46
|
+
* @deprecated Use formatBatchHeader from response.ts instead
|
|
80
47
|
*/
|
|
81
48
|
export declare function buildBatchHeader(title: string, count: number, tokensPerItem: number, totalBudget: number): string;
|
|
82
49
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* @param successful - Number of successful items
|
|
86
|
-
* @param failed - Number of failed items
|
|
87
|
-
* @param batches - Number of batches processed
|
|
88
|
-
* @param extras - Optional extra status items
|
|
89
|
-
* @returns Formatted status line
|
|
50
|
+
* @deprecated Use formatBatchHeader from response.ts instead
|
|
90
51
|
*/
|
|
91
52
|
export declare function buildStatusLine(successful: number, failed: number, batches: number, extras?: string[]): string;
|
|
92
53
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/tools/utils.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/tools/utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGlG,OAAO,EACL,aAAa,EACb,WAAW,EACX,iBAAiB,EACjB,UAAU,EACV,eAAe,EACf,cAAc,EACd,YAAY,EACZ,KAAK,sBAAsB,EAC3B,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,GACxB,MAAM,sBAAsB,CAAC;AAM9B;;;GAGG;AACH,eAAO,MAAM,aAAa;IACxB,2CAA2C;;IAE3C,0CAA0C;;IAE1C,kDAAkD;;CAE1C,CAAC;AAMX;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE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