@youdotcom-oss/api 0.1.0 → 0.2.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 +36 -36
- package/bin/cli.js +233 -403
- package/package.json +2 -2
- package/src/cli.ts +92 -21
- package/src/contents/contents.schemas.ts +8 -7
- package/src/contents/tests/contents.request.spec.ts +109 -0
- package/src/contents/tests/contents.schema-validation.spec.ts +75 -0
- package/src/deep-search/deep-search.schemas.ts +48 -0
- package/src/deep-search/deep-search.utils.ts +75 -0
- package/src/main.ts +4 -3
- package/src/search/search.schemas.ts +65 -6
- package/src/search/search.utils.ts +6 -28
- package/src/search/tests/search.request.spec.ts +122 -0
- package/src/search/tests/search.schema-validation.spec.ts +152 -0
- package/src/search/tests/{search.utils.spec.ts → search.utils.docker.ts} +0 -10
- package/src/shared/api.constants.ts +1 -1
- package/src/shared/check-response-for-errors.ts +1 -1
- package/src/shared/command-runner.ts +95 -0
- package/src/shared/dry-run-utils.ts +141 -0
- package/src/shared/tests/command-runner.spec.ts +210 -0
- package/src/shared/use-get-user-agents.ts +1 -1
- package/src/commands/contents.ts +0 -52
- package/src/commands/express.ts +0 -52
- package/src/commands/search.ts +0 -52
- package/src/express/express.schemas.ts +0 -85
- package/src/express/express.utils.ts +0 -113
- package/src/express/tests/express.utils.spec.ts +0 -83
- /package/src/contents/tests/{contents.utils.spec.ts → contents.utils.docker.ts} +0 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import * as z from 'zod'
|
|
3
|
+
import { runCommand } from '../command-runner.ts'
|
|
4
|
+
|
|
5
|
+
describe('runCommand', () => {
|
|
6
|
+
const TestSchema = z.object({
|
|
7
|
+
value: z.string(),
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
let originalApiKey: string | undefined
|
|
11
|
+
|
|
12
|
+
beforeAll(() => {
|
|
13
|
+
// Save original API key
|
|
14
|
+
originalApiKey = process.env.YDC_API_KEY
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
afterAll(() => {
|
|
18
|
+
// Restore original API key
|
|
19
|
+
if (originalApiKey) {
|
|
20
|
+
process.env.YDC_API_KEY = originalApiKey
|
|
21
|
+
} else {
|
|
22
|
+
delete process.env.YDC_API_KEY
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('outputs JSON schema when --schema flag is provided', async () => {
|
|
27
|
+
const originalExit = process.exit
|
|
28
|
+
const originalLog = console.log
|
|
29
|
+
|
|
30
|
+
process.exit = (() => {
|
|
31
|
+
throw new Error('EXIT')
|
|
32
|
+
}) as typeof process.exit
|
|
33
|
+
|
|
34
|
+
let outputData = ''
|
|
35
|
+
console.log = (data: string) => {
|
|
36
|
+
outputData = data
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
await runCommand(['--schema'], {
|
|
41
|
+
schema: TestSchema,
|
|
42
|
+
handler: async () => ({ result: 'test' }),
|
|
43
|
+
})
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error instanceof Error && error.message === 'EXIT') {
|
|
46
|
+
const schema = JSON.parse(outputData)
|
|
47
|
+
expect(schema.type).toBe('object')
|
|
48
|
+
expect(schema.properties).toBeDefined()
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Restore original functions
|
|
53
|
+
process.exit = originalExit
|
|
54
|
+
console.log = originalLog
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
test('throws error when --json flag is missing', async () => {
|
|
58
|
+
expect(async () => {
|
|
59
|
+
await runCommand([], {
|
|
60
|
+
schema: TestSchema,
|
|
61
|
+
handler: async () => ({ result: 'test' }),
|
|
62
|
+
})
|
|
63
|
+
}).toThrow('--json flag is required')
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
test('throws error when JSON is malformed', async () => {
|
|
67
|
+
expect(async () => {
|
|
68
|
+
await runCommand(['--json', 'invalid-json'], {
|
|
69
|
+
schema: TestSchema,
|
|
70
|
+
handler: async () => ({ result: 'test' }),
|
|
71
|
+
})
|
|
72
|
+
}).toThrow()
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test('throws error when API key is missing from both flag and env', async () => {
|
|
76
|
+
const originalApiKey = process.env.YDC_API_KEY
|
|
77
|
+
delete process.env.YDC_API_KEY
|
|
78
|
+
|
|
79
|
+
expect(async () => {
|
|
80
|
+
await runCommand(['--json', '{"value":"test"}'], {
|
|
81
|
+
schema: TestSchema,
|
|
82
|
+
handler: async () => ({ result: 'test' }),
|
|
83
|
+
})
|
|
84
|
+
}).toThrow('YDC_API_KEY environment variable is required')
|
|
85
|
+
|
|
86
|
+
// Restore original value
|
|
87
|
+
if (originalApiKey) {
|
|
88
|
+
process.env.YDC_API_KEY = originalApiKey
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
test('resolves API key from --api-key flag over environment', async () => {
|
|
93
|
+
const originalLog = console.log
|
|
94
|
+
process.env.YDC_API_KEY = 'env-key'
|
|
95
|
+
|
|
96
|
+
let capturedKey = ''
|
|
97
|
+
console.log = () => {
|
|
98
|
+
// Suppress output
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
await runCommand(['--json', '{"value":"test"}', '--api-key', 'flag-key'], {
|
|
102
|
+
schema: TestSchema,
|
|
103
|
+
handler: async ({ YDC_API_KEY }) => {
|
|
104
|
+
capturedKey = YDC_API_KEY
|
|
105
|
+
return { result: 'test' }
|
|
106
|
+
},
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
expect(capturedKey).toBe('flag-key')
|
|
110
|
+
|
|
111
|
+
// Restore original function
|
|
112
|
+
console.log = originalLog
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
test('throws error when schema validation fails', async () => {
|
|
116
|
+
process.env.YDC_API_KEY = 'test-key'
|
|
117
|
+
|
|
118
|
+
expect(async () => {
|
|
119
|
+
await runCommand(['--json', '{"invalid":"field"}'], {
|
|
120
|
+
schema: TestSchema,
|
|
121
|
+
handler: async () => ({ result: 'test' }),
|
|
122
|
+
})
|
|
123
|
+
}).toThrow()
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
test('calls handler when all validations pass', async () => {
|
|
127
|
+
const originalLog = console.log
|
|
128
|
+
process.env.YDC_API_KEY = 'test-key'
|
|
129
|
+
|
|
130
|
+
let handlerCalled = false
|
|
131
|
+
let outputData = ''
|
|
132
|
+
console.log = (data: string) => {
|
|
133
|
+
outputData = data
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
await runCommand(['--json', '{"value":"test"}'], {
|
|
137
|
+
schema: TestSchema,
|
|
138
|
+
handler: async () => {
|
|
139
|
+
handlerCalled = true
|
|
140
|
+
return { result: 'success' }
|
|
141
|
+
},
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
expect(handlerCalled).toBe(true)
|
|
145
|
+
const output = JSON.parse(outputData)
|
|
146
|
+
expect(output.result).toBe('success')
|
|
147
|
+
|
|
148
|
+
// Restore original function
|
|
149
|
+
console.log = originalLog
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
test('calls dryRunHandler when --dry-run flag is provided', async () => {
|
|
153
|
+
const originalLog = console.log
|
|
154
|
+
process.env.YDC_API_KEY = 'test-key'
|
|
155
|
+
|
|
156
|
+
let dryRunCalled = false
|
|
157
|
+
let handlerCalled = false
|
|
158
|
+
let outputData = ''
|
|
159
|
+
console.log = (data: string) => {
|
|
160
|
+
outputData = data
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
await runCommand(['--json', '{"value":"test"}', '--dry-run'], {
|
|
164
|
+
schema: TestSchema,
|
|
165
|
+
handler: async () => {
|
|
166
|
+
handlerCalled = true
|
|
167
|
+
return { result: 'success' }
|
|
168
|
+
},
|
|
169
|
+
dryRunHandler: () => {
|
|
170
|
+
dryRunCalled = true
|
|
171
|
+
return {
|
|
172
|
+
url: 'https://test.com',
|
|
173
|
+
method: 'GET',
|
|
174
|
+
headers: { 'X-API-Key': 'test-key' },
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
expect(dryRunCalled).toBe(true)
|
|
180
|
+
expect(handlerCalled).toBe(false)
|
|
181
|
+
const output = JSON.parse(outputData)
|
|
182
|
+
expect(output.url).toBe('https://test.com')
|
|
183
|
+
|
|
184
|
+
// Restore original function
|
|
185
|
+
console.log = originalLog
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test('respects --client flag for User-Agent', async () => {
|
|
189
|
+
const originalLog = console.log
|
|
190
|
+
process.env.YDC_API_KEY = 'test-key'
|
|
191
|
+
|
|
192
|
+
let capturedUserAgent = ''
|
|
193
|
+
console.log = () => {
|
|
194
|
+
// Suppress output
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
await runCommand(['--json', '{"value":"test"}', '--client', 'TestClient'], {
|
|
198
|
+
schema: TestSchema,
|
|
199
|
+
handler: async ({ getUserAgent }) => {
|
|
200
|
+
capturedUserAgent = getUserAgent()
|
|
201
|
+
return { result: 'test' }
|
|
202
|
+
},
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
expect(capturedUserAgent).toContain('TestClient')
|
|
206
|
+
|
|
207
|
+
// Restore original function
|
|
208
|
+
console.log = originalLog
|
|
209
|
+
})
|
|
210
|
+
})
|
package/src/commands/contents.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { parseArgs } from 'node:util'
|
|
2
|
-
import * as z from 'zod'
|
|
3
|
-
import { ContentsQuerySchema } from '../contents/contents.schemas.ts'
|
|
4
|
-
import { fetchContents } from '../contents/contents.utils.ts'
|
|
5
|
-
import { useGetUserAgent } from '../shared/use-get-user-agents.ts'
|
|
6
|
-
|
|
7
|
-
export const contentsCommand = async (args: string[]) => {
|
|
8
|
-
// Handle --schema flag
|
|
9
|
-
if (args.includes('--schema')) {
|
|
10
|
-
console.log(JSON.stringify(z.toJSONSchema(ContentsQuerySchema)))
|
|
11
|
-
process.exit(0)
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// Parse flags with Node's built-in parseArgs
|
|
15
|
-
const { values } = parseArgs({
|
|
16
|
-
args,
|
|
17
|
-
options: {
|
|
18
|
-
json: { type: 'string' },
|
|
19
|
-
'api-key': { type: 'string' },
|
|
20
|
-
client: { type: 'string' },
|
|
21
|
-
},
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
// --json is required
|
|
25
|
-
if (!values.json) {
|
|
26
|
-
throw new Error('--json flag is required')
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Parse JSON and validate with schema
|
|
30
|
-
const query = JSON.parse(values.json)
|
|
31
|
-
const apiKey = values['api-key']
|
|
32
|
-
const client = values.client || process.env.YDC_CLIENT
|
|
33
|
-
|
|
34
|
-
// Get API key from options or environment
|
|
35
|
-
const YDC_API_KEY = apiKey || process.env.YDC_API_KEY
|
|
36
|
-
if (!YDC_API_KEY) {
|
|
37
|
-
throw new Error('YDC_API_KEY environment variable is required')
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Validate with schema (includes urls validation)
|
|
41
|
-
const contentsQuery = ContentsQuerySchema.parse(query)
|
|
42
|
-
|
|
43
|
-
// Fetch contents
|
|
44
|
-
const response = await fetchContents({
|
|
45
|
-
contentsQuery,
|
|
46
|
-
YDC_API_KEY,
|
|
47
|
-
getUserAgent: useGetUserAgent(client),
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
// Output response to stdout (success)
|
|
51
|
-
console.log(JSON.stringify(response))
|
|
52
|
-
}
|
package/src/commands/express.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { parseArgs } from 'node:util'
|
|
2
|
-
import * as z from 'zod'
|
|
3
|
-
import { ExpressAgentInputSchema } from '../express/express.schemas.ts'
|
|
4
|
-
import { callExpressAgent } from '../express/express.utils.ts'
|
|
5
|
-
import { useGetUserAgent } from '../shared/use-get-user-agents.ts'
|
|
6
|
-
|
|
7
|
-
export const expressCommand = async (args: string[]) => {
|
|
8
|
-
// Handle --schema flag
|
|
9
|
-
if (args.includes('--schema')) {
|
|
10
|
-
console.log(JSON.stringify(z.toJSONSchema(ExpressAgentInputSchema)))
|
|
11
|
-
process.exit(0)
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// Parse flags with Node's built-in parseArgs
|
|
15
|
-
const { values } = parseArgs({
|
|
16
|
-
args,
|
|
17
|
-
options: {
|
|
18
|
-
json: { type: 'string' },
|
|
19
|
-
'api-key': { type: 'string' },
|
|
20
|
-
client: { type: 'string' },
|
|
21
|
-
},
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
// --json is required
|
|
25
|
-
if (!values.json) {
|
|
26
|
-
throw new Error('--json flag is required')
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Parse JSON and validate with schema
|
|
30
|
-
const input = JSON.parse(values.json)
|
|
31
|
-
const apiKey = values['api-key']
|
|
32
|
-
const client = values.client || process.env.YDC_CLIENT
|
|
33
|
-
|
|
34
|
-
// Get API key from options or environment
|
|
35
|
-
const YDC_API_KEY = apiKey || process.env.YDC_API_KEY
|
|
36
|
-
if (!YDC_API_KEY) {
|
|
37
|
-
throw new Error('YDC_API_KEY environment variable is required')
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Validate with schema (includes input validation)
|
|
41
|
-
const agentInput = ExpressAgentInputSchema.parse(input)
|
|
42
|
-
|
|
43
|
-
// Call agent
|
|
44
|
-
const response = await callExpressAgent({
|
|
45
|
-
agentInput,
|
|
46
|
-
YDC_API_KEY,
|
|
47
|
-
getUserAgent: useGetUserAgent(client),
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
// Output response to stdout (success)
|
|
51
|
-
console.log(JSON.stringify(response))
|
|
52
|
-
}
|
package/src/commands/search.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { parseArgs } from 'node:util'
|
|
2
|
-
import * as z from 'zod'
|
|
3
|
-
import { SearchQuerySchema } from '../search/search.schemas.ts'
|
|
4
|
-
import { fetchSearchResults } from '../search/search.utils.ts'
|
|
5
|
-
import { useGetUserAgent } from '../shared/use-get-user-agents.ts'
|
|
6
|
-
|
|
7
|
-
export const searchCommand = async (args: string[]) => {
|
|
8
|
-
// Handle --schema flag
|
|
9
|
-
if (args.includes('--schema')) {
|
|
10
|
-
console.log(JSON.stringify(z.toJSONSchema(SearchQuerySchema)))
|
|
11
|
-
process.exit(0)
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// Parse flags with Node's built-in parseArgs
|
|
15
|
-
const { values } = parseArgs({
|
|
16
|
-
args,
|
|
17
|
-
options: {
|
|
18
|
-
json: { type: 'string' },
|
|
19
|
-
'api-key': { type: 'string' },
|
|
20
|
-
client: { type: 'string' },
|
|
21
|
-
},
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
// --json is required
|
|
25
|
-
if (!values.json) {
|
|
26
|
-
throw new Error('--json flag is required')
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Parse JSON and validate with schema
|
|
30
|
-
const query = JSON.parse(values.json)
|
|
31
|
-
const apiKey = values['api-key']
|
|
32
|
-
const client = values.client || process.env.YDC_CLIENT
|
|
33
|
-
|
|
34
|
-
// Get API key from options or environment
|
|
35
|
-
const YDC_API_KEY = apiKey || process.env.YDC_API_KEY
|
|
36
|
-
if (!YDC_API_KEY) {
|
|
37
|
-
throw new Error('YDC_API_KEY environment variable is required')
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Validate with schema (includes query validation)
|
|
41
|
-
const searchQuery = SearchQuerySchema.parse(query)
|
|
42
|
-
|
|
43
|
-
// Fetch results
|
|
44
|
-
const response = await fetchSearchResults({
|
|
45
|
-
searchQuery,
|
|
46
|
-
YDC_API_KEY,
|
|
47
|
-
getUserAgent: useGetUserAgent(client),
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
// Output response to stdout (success)
|
|
51
|
-
console.log(JSON.stringify(response))
|
|
52
|
-
}
|
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import * as z from 'zod'
|
|
2
|
-
|
|
3
|
-
export const ExpressAgentInputSchema = z.object({
|
|
4
|
-
input: z.string().min(1, 'Input is required').describe('Query or prompt'),
|
|
5
|
-
tools: z
|
|
6
|
-
.array(
|
|
7
|
-
z.object({
|
|
8
|
-
type: z.enum(['web_search']).describe('Tool type'),
|
|
9
|
-
}),
|
|
10
|
-
)
|
|
11
|
-
.optional()
|
|
12
|
-
.describe('Tools (web search only)'),
|
|
13
|
-
})
|
|
14
|
-
|
|
15
|
-
export type ExpressAgentInput = z.infer<typeof ExpressAgentInputSchema>
|
|
16
|
-
|
|
17
|
-
// API Response Schema - Validates the full response from You.com API
|
|
18
|
-
|
|
19
|
-
// Search result content item from web_search.results
|
|
20
|
-
// Note: thumbnail_url, source_type, and provider are API-only pass-through fields not used in MCP output
|
|
21
|
-
const ApiSearchResultItemSchema = z.object({
|
|
22
|
-
source_type: z.string().nullable().optional(),
|
|
23
|
-
citation_uri: z.string().optional(), // Used as fallback for url in transformation
|
|
24
|
-
url: z.string(),
|
|
25
|
-
title: z.string(),
|
|
26
|
-
snippet: z.string(),
|
|
27
|
-
thumbnail_url: z.string().nullable().optional(), // API-only, not transformed to MCP output
|
|
28
|
-
provider: z.string().nullable().optional(), // API-only, not transformed to MCP output
|
|
29
|
-
})
|
|
30
|
-
|
|
31
|
-
// Union of possible output item types from API
|
|
32
|
-
const ExpressAgentApiOutputItemSchema = z.union([
|
|
33
|
-
// web_search.results type - has content array, no text
|
|
34
|
-
z.object({
|
|
35
|
-
type: z.literal('web_search.results'),
|
|
36
|
-
content: z.array(ApiSearchResultItemSchema),
|
|
37
|
-
}),
|
|
38
|
-
// message.answer type - has text, no content
|
|
39
|
-
z.object({
|
|
40
|
-
type: z.literal('message.answer'),
|
|
41
|
-
text: z.string(),
|
|
42
|
-
}),
|
|
43
|
-
])
|
|
44
|
-
|
|
45
|
-
export const ExpressAgentApiResponseSchema = z
|
|
46
|
-
.object({
|
|
47
|
-
output: z.array(ExpressAgentApiOutputItemSchema),
|
|
48
|
-
agent: z.string().optional().describe('Agent identifier'),
|
|
49
|
-
mode: z.string().optional().describe('Agent mode'),
|
|
50
|
-
input: z
|
|
51
|
-
.array(
|
|
52
|
-
z.object({
|
|
53
|
-
role: z.enum(['user']).describe('User role'),
|
|
54
|
-
content: z.string().describe('User question'),
|
|
55
|
-
}),
|
|
56
|
-
)
|
|
57
|
-
.optional()
|
|
58
|
-
.describe('Input messages'),
|
|
59
|
-
})
|
|
60
|
-
.passthrough()
|
|
61
|
-
|
|
62
|
-
export type ExpressAgentApiResponse = z.infer<typeof ExpressAgentApiResponseSchema>
|
|
63
|
-
|
|
64
|
-
// MCP Output Schema - Defines what we return to the MCP client (answer + optional search results, token efficient)
|
|
65
|
-
|
|
66
|
-
// Search result item for MCP output
|
|
67
|
-
const McpSearchResultItemSchema = z.object({
|
|
68
|
-
url: z.string().describe('URL'),
|
|
69
|
-
title: z.string().describe('Title'),
|
|
70
|
-
snippet: z.string().describe('Snippet'),
|
|
71
|
-
})
|
|
72
|
-
|
|
73
|
-
// MCP response structure: answer (always) + results (optional when web_search used)
|
|
74
|
-
const ExpressAgentMcpResponseSchema = z.object({
|
|
75
|
-
answer: z.string().describe('AI answer'),
|
|
76
|
-
results: z
|
|
77
|
-
.object({
|
|
78
|
-
web: z.array(McpSearchResultItemSchema).describe('Web results'),
|
|
79
|
-
})
|
|
80
|
-
.optional()
|
|
81
|
-
.describe('Search results'),
|
|
82
|
-
agent: z.string().optional().describe('Agent ID'),
|
|
83
|
-
})
|
|
84
|
-
|
|
85
|
-
export type ExpressAgentMcpResponse = z.infer<typeof ExpressAgentMcpResponseSchema>
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
import { EXPRESS_API_URL } from '../shared/api.constants.ts'
|
|
2
|
-
import type { GetUserAgent } from '../shared/api.types.ts'
|
|
3
|
-
import { checkResponseForErrors } from '../shared/check-response-for-errors.ts'
|
|
4
|
-
import {
|
|
5
|
-
type ExpressAgentApiResponse,
|
|
6
|
-
ExpressAgentApiResponseSchema,
|
|
7
|
-
type ExpressAgentInput,
|
|
8
|
-
type ExpressAgentMcpResponse,
|
|
9
|
-
} from './express.schemas.ts'
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Checks response status and throws appropriate errors for agent API calls
|
|
13
|
-
*/
|
|
14
|
-
const agentThrowOnFailedStatus = async (response: Response) => {
|
|
15
|
-
const errorCode = response.status
|
|
16
|
-
|
|
17
|
-
const errorData = (await response.json()) as {
|
|
18
|
-
errors?: Array<{ detail?: string }>
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
if (errorCode === 400) {
|
|
22
|
-
throw new Error(`Bad Request:\n${JSON.stringify(errorData)}`)
|
|
23
|
-
} else if (errorCode === 401) {
|
|
24
|
-
throw new Error(
|
|
25
|
-
`Unauthorized: The Agent APIs require a valid You.com API key with agent access. Ensure your YDC_API_KEY has permissions for agent endpoints.`,
|
|
26
|
-
)
|
|
27
|
-
} else if (errorCode === 403) {
|
|
28
|
-
throw new Error(`Forbidden: You are not allowed to use the requested tool for this agent or tenant`)
|
|
29
|
-
} else if (errorCode === 429) {
|
|
30
|
-
throw new Error('Rate limited by You.com API. Please try again later.')
|
|
31
|
-
}
|
|
32
|
-
throw new Error(`Failed to call agent. Error code: ${errorCode}`)
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export const callExpressAgent = async ({
|
|
36
|
-
YDC_API_KEY = process.env.YDC_API_KEY,
|
|
37
|
-
agentInput: { input, tools },
|
|
38
|
-
getUserAgent,
|
|
39
|
-
}: {
|
|
40
|
-
agentInput: ExpressAgentInput
|
|
41
|
-
YDC_API_KEY?: string
|
|
42
|
-
getUserAgent: GetUserAgent
|
|
43
|
-
}) => {
|
|
44
|
-
const requestBody: {
|
|
45
|
-
agent: string
|
|
46
|
-
input: string
|
|
47
|
-
stream: boolean
|
|
48
|
-
tools?: Array<{ type: 'web_search' }>
|
|
49
|
-
} = {
|
|
50
|
-
agent: 'express',
|
|
51
|
-
input,
|
|
52
|
-
stream: false, // Use non-streaming JSON response
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// Only include tools if provided
|
|
56
|
-
if (tools) {
|
|
57
|
-
requestBody.tools = tools
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const options = {
|
|
61
|
-
method: 'POST',
|
|
62
|
-
headers: new Headers({
|
|
63
|
-
Authorization: `Bearer ${YDC_API_KEY || ''}`,
|
|
64
|
-
'Content-Type': 'application/json',
|
|
65
|
-
Accept: 'application/json',
|
|
66
|
-
'User-Agent': getUserAgent(),
|
|
67
|
-
}),
|
|
68
|
-
body: JSON.stringify(requestBody),
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const response = await fetch(EXPRESS_API_URL, options)
|
|
72
|
-
|
|
73
|
-
if (!response.ok) {
|
|
74
|
-
await agentThrowOnFailedStatus(response)
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Parse JSON response directly
|
|
78
|
-
const jsonResponse = await response.json()
|
|
79
|
-
|
|
80
|
-
// Check for error field in response
|
|
81
|
-
checkResponseForErrors(jsonResponse)
|
|
82
|
-
|
|
83
|
-
// Validate API response schema (full response with all fields)
|
|
84
|
-
const apiResponse: ExpressAgentApiResponse = ExpressAgentApiResponseSchema.parse(jsonResponse)
|
|
85
|
-
|
|
86
|
-
// Find the answer (always present as message.answer, validated by Zod)
|
|
87
|
-
const answerItem = apiResponse.output.find((item) => item.type === 'message.answer')
|
|
88
|
-
if (!answerItem) {
|
|
89
|
-
throw new Error('Express API response missing required message.answer item')
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Find search results (optional, present when web_search tool is used)
|
|
93
|
-
const searchItem = apiResponse.output.find((item) => item.type === 'web_search.results')
|
|
94
|
-
|
|
95
|
-
// Transform API response to MCP output format (answer + optional search results, token efficient)
|
|
96
|
-
const mcpResponse: ExpressAgentMcpResponse = {
|
|
97
|
-
answer: answerItem.text,
|
|
98
|
-
agent: apiResponse.agent,
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Transform search results if present
|
|
102
|
-
if (searchItem && 'content' in searchItem && Array.isArray(searchItem.content)) {
|
|
103
|
-
mcpResponse.results = {
|
|
104
|
-
web: searchItem.content.map((item) => ({
|
|
105
|
-
url: item.url || item.citation_uri || '',
|
|
106
|
-
title: item.title || '',
|
|
107
|
-
snippet: item.snippet || '',
|
|
108
|
-
})),
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return mcpResponse
|
|
113
|
-
}
|
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import { describe, expect, setDefaultTimeout, test } from 'bun:test'
|
|
2
|
-
import { callExpressAgent } from '../express.utils.ts'
|
|
3
|
-
|
|
4
|
-
const getUserAgent = () => 'API/test (You.com;TEST)'
|
|
5
|
-
|
|
6
|
-
setDefaultTimeout(20_000)
|
|
7
|
-
|
|
8
|
-
describe('callExpressAgent', () => {
|
|
9
|
-
test(
|
|
10
|
-
'returns answer only (WITHOUT web_search tools)',
|
|
11
|
-
async () => {
|
|
12
|
-
const result = await callExpressAgent({
|
|
13
|
-
agentInput: { input: 'What is machine learning?' },
|
|
14
|
-
getUserAgent,
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
// Verify MCP response structure
|
|
18
|
-
expect(result).toHaveProperty('answer')
|
|
19
|
-
expect(typeof result.answer).toBe('string')
|
|
20
|
-
expect(result.answer.length).toBeGreaterThan(0)
|
|
21
|
-
|
|
22
|
-
// Should NOT have results when web_search is not used
|
|
23
|
-
expect(result.results).toBeUndefined()
|
|
24
|
-
|
|
25
|
-
expect(result.agent).toBe('express')
|
|
26
|
-
},
|
|
27
|
-
{ retry: 2 },
|
|
28
|
-
)
|
|
29
|
-
|
|
30
|
-
test(
|
|
31
|
-
'returns answer and search results (WITH web_search tools)',
|
|
32
|
-
async () => {
|
|
33
|
-
const result = await callExpressAgent({
|
|
34
|
-
agentInput: {
|
|
35
|
-
input: 'Latest developments in quantum computing',
|
|
36
|
-
tools: [{ type: 'web_search' }],
|
|
37
|
-
},
|
|
38
|
-
getUserAgent,
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
// Verify MCP response has both answer and results
|
|
42
|
-
expect(result).toHaveProperty('answer')
|
|
43
|
-
expect(typeof result.answer).toBe('string')
|
|
44
|
-
expect(result.answer.length).toBeGreaterThan(0)
|
|
45
|
-
|
|
46
|
-
expect(result).toHaveProperty('results')
|
|
47
|
-
expect(result.results).toHaveProperty('web')
|
|
48
|
-
expect(Array.isArray(result.results?.web)).toBe(true)
|
|
49
|
-
expect(result.results?.web.length).toBeGreaterThan(0)
|
|
50
|
-
|
|
51
|
-
// Verify each search result has required fields
|
|
52
|
-
const firstResult = result.results?.web[0]
|
|
53
|
-
expect(firstResult).toHaveProperty('url')
|
|
54
|
-
expect(firstResult).toHaveProperty('title')
|
|
55
|
-
expect(firstResult).toHaveProperty('snippet')
|
|
56
|
-
expect(typeof firstResult?.url).toBe('string')
|
|
57
|
-
expect(typeof firstResult?.title).toBe('string')
|
|
58
|
-
expect(typeof firstResult?.snippet).toBe('string')
|
|
59
|
-
expect(firstResult?.url.length).toBeGreaterThan(0)
|
|
60
|
-
expect(firstResult?.title.length).toBeGreaterThan(0)
|
|
61
|
-
|
|
62
|
-
expect(result.agent).toBe('express')
|
|
63
|
-
},
|
|
64
|
-
{ timeout: 30_000, retry: 2 },
|
|
65
|
-
)
|
|
66
|
-
|
|
67
|
-
test(
|
|
68
|
-
'works without optional parameters',
|
|
69
|
-
async () => {
|
|
70
|
-
const result = await callExpressAgent({
|
|
71
|
-
agentInput: { input: 'What is the capital of France?' },
|
|
72
|
-
getUserAgent,
|
|
73
|
-
// No progressToken or sendProgress provided
|
|
74
|
-
})
|
|
75
|
-
|
|
76
|
-
// Should work normally without progress tracking
|
|
77
|
-
expect(result).toHaveProperty('answer')
|
|
78
|
-
expect(result.answer.length).toBeGreaterThan(0)
|
|
79
|
-
expect(result.agent).toBe('express')
|
|
80
|
-
},
|
|
81
|
-
{ retry: 2 },
|
|
82
|
-
)
|
|
83
|
-
})
|
|
File without changes
|