@evolinkai/cli 0.7.0 → 0.8.1
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 +35 -6
- package/package.json +27 -8
- package/skills/evolink-cli/SKILL.md +5 -5
- package/skills/evolink-cli/references/capabilities.md +1 -1
- package/src/api.mjs +59 -0
- package/src/auth.mjs +6 -7
- package/src/cli.mjs +34 -30
- package/src/doctor.mjs +9 -6
- package/src/errors.mjs +21 -13
- package/src/files.mjs +61 -6
- package/src/help.mjs +8 -8
- package/src/media.mjs +11 -9
- package/src/network.mjs +12 -1
- package/src/oauth.mjs +90 -0
- package/src/platform/LICENSE +178 -0
- package/src/platform/NOTICE +6 -0
- package/src/platform/core/src/config.js +95 -0
- package/src/platform/core/src/data/model-constraints.js +37 -0
- package/src/platform/core/src/data/model-params.generated.js +4 -0
- package/src/platform/core/src/data/model-params.js +28 -0
- package/src/platform/core/src/platform-client.js +56 -0
- package/src/platform/core/src/platform-operations.js +22 -0
- package/src/platform/core/src/request-context.js +53 -0
- package/src/platform/core/src/services/api-client.js +232 -0
- package/src/platform/core/src/services/catalog-client.js +45 -0
- package/src/platform/core/src/services/error-handler.js +452 -0
- package/src/platform/core/src/services/file-client.js +165 -0
- package/src/platform/core/src/services/http-policy.js +186 -0
- package/src/platform/core/src/services/model-capabilities.js +24 -0
- package/src/platform/core/src/services/model-catalog.js +68 -0
- package/src/platform/core/src/services/model-recommendations.js +35 -0
- package/src/platform/core/src/services/param-validator.js +201 -0
- package/src/platform/core/src/services/pricing-client.js +451 -0
- package/src/platform/core/src/services/public-error.js +63 -0
- package/src/platform/core/src/services/utm.js +65 -0
- package/src/platform/core/src/tool-guidance.js +50 -0
- package/src/platform/core/src/tools/check-balance.js +90 -0
- package/src/platform/core/src/tools/discovery.js +86 -0
- package/src/platform/core/src/tools/estimate-cost.js +136 -0
- package/src/platform/core/src/tools/generate.js +237 -0
- package/src/platform/core/src/tools/get-model.js +146 -0
- package/src/platform/core/src/tools/get-task.js +57 -0
- package/src/platform/core/src/tools/list-tasks.js +170 -0
- package/src/platform/core/src/tools/search-models.js +115 -0
- package/src/platform/core/src/tools/shared.js +158 -0
- package/src/platform/core/src/tools/task-billing.js +31 -0
- package/src/platform/core/src/tools/task-format.js +264 -0
- package/src/platform/core/src/tools/task-usage.js +108 -0
- package/src/platform/core/src/version.js +4 -0
- package/src/platform/source.json +84 -0
- package/src/setup.mjs +9 -5
- package/src/mcp.mjs +0 -43
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
|
|
3
|
+
import { currentCredentialMode } from '../request-context.js';
|
|
4
|
+
import { getCredits } from '../services/api-client.js';
|
|
5
|
+
import { CREDITS_PER_USD } from '../services/error-handler.js';
|
|
6
|
+
import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
|
|
7
|
+
import { trackedLink } from '../services/utm.js';
|
|
8
|
+
import { READ_ONLY, dailyLimitOf, errorResult, money, ok, usdOf } from './shared.js';
|
|
9
|
+
/** Below this the user is told the balance, or the limit, is nearly gone (about $1). */
|
|
10
|
+
const LOW_BALANCE_CREDITS = CREDITS_PER_USD;
|
|
11
|
+
export function registerCheckBalance(server, config) {
|
|
12
|
+
server.registerTool('check_balance', {
|
|
13
|
+
title: 'Check balance',
|
|
14
|
+
description: [
|
|
15
|
+
'Show the EvoLink account balance and what has been spent: by the shared EvoLink MCP OAuth key in total (CLI and all assistants connected by sign-in) or by this API key, with its limit if one is set. Free.',
|
|
16
|
+
'Also a quick way to confirm the connection works.',
|
|
17
|
+
'Credits: 68 credits ≈ $1.',
|
|
18
|
+
].join(' '),
|
|
19
|
+
inputSchema: {},
|
|
20
|
+
annotations: { title: 'Check balance', ...READ_ONLY },
|
|
21
|
+
}, async () => {
|
|
22
|
+
try {
|
|
23
|
+
const credits = await getCredits(config);
|
|
24
|
+
// A signed-in connection spends the account's MCP key: its spend and limit cover every connected assistant.
|
|
25
|
+
const signedIn = currentCredentialMode() === 'signed_in';
|
|
26
|
+
const who = signedIn ? 'EvoLink MCP (CLI and all assistants connected to this account)' : 'This API key';
|
|
27
|
+
const limitName = signedIn ? 'the EvoLink MCP limit' : 'its limit';
|
|
28
|
+
const balance = Math.max(0, credits.user.remaining_credits);
|
|
29
|
+
const lines = [`Account balance: ${money(balance)}`];
|
|
30
|
+
const structured = {
|
|
31
|
+
account_balance_credits: balance,
|
|
32
|
+
account_balance_usd: usdOf(balance),
|
|
33
|
+
spent_scope: signedIn ? 'mcp' : 'api_key',
|
|
34
|
+
spent_credits: credits.token.used_credits,
|
|
35
|
+
spent_usd: usdOf(credits.token.used_credits),
|
|
36
|
+
has_limit: !credits.token.unlimited_credits,
|
|
37
|
+
top_up_url: trackedLink(TOP_UP_URL, 'top_up'),
|
|
38
|
+
...(signedIn ? {
|
|
39
|
+
mcp_settings_url: trackedLink(MCP_CONSOLE_URL, 'api_keys'),
|
|
40
|
+
authorization: { mode: 'oauth', key_name: MCP_KEY_NAME, key_scope: 'account',
|
|
41
|
+
shared_clients: ['cli', 'mcp'], quota_scope: 'shared_account_key', permission_scope: 'shared_account_key',
|
|
42
|
+
pause_scope: 'shared_account_key', logout_scope: 'current_oauth_session' },
|
|
43
|
+
} : {}),
|
|
44
|
+
};
|
|
45
|
+
if (signedIn)
|
|
46
|
+
lines.push('CLI and MCP share this account key: its total/daily limits, permissions and pause apply to both. Logging out revokes only that OAuth session; other sessions retain access.');
|
|
47
|
+
const daily = dailyLimitOf(credits.token);
|
|
48
|
+
if (credits.token.unlimited_credits) {
|
|
49
|
+
// A daily limit, if any, is named on its own line below: do not say that only the balance applies.
|
|
50
|
+
const spent = money(credits.token.used_credits);
|
|
51
|
+
lines.push(signedIn
|
|
52
|
+
? (daily ? `${who} has spent ${spent}; no total EvoLink MCP limit is set.` : `${who} has spent ${spent}; no EvoLink MCP limit is set, so only the account balance applies.`)
|
|
53
|
+
: (daily ? `${who} has spent ${spent} and has no total spending limit of its own.` : `${who} has spent ${spent} and has no spending limit of its own (the account balance applies).`));
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
const left = Math.max(0, credits.token.remaining_credits);
|
|
57
|
+
lines.push(`${who} has spent ${money(credits.token.used_credits)}; ${money(left)} of ${limitName} is left.`);
|
|
58
|
+
structured.limit_remaining_credits = left;
|
|
59
|
+
structured.limit_remaining_usd = usdOf(left);
|
|
60
|
+
if (left < LOW_BALANCE_CREDITS) {
|
|
61
|
+
const state = left <= 0 ? 'used up' : 'nearly used up';
|
|
62
|
+
lines.push(signedIn
|
|
63
|
+
? `The EvoLink MCP limit is ${state} (it is a limit, not the account balance); the user can raise it at ${trackedLink(MCP_CONSOLE_URL, 'api_keys')} (the key named "${MCP_KEY_NAME}").`
|
|
64
|
+
: `This API key's limit is ${state}; raise it at ${trackedLink(API_KEYS_URL, 'api_keys')}.`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (daily) {
|
|
68
|
+
const resets = `it resets at midnight${daily.zone ? ` (${daily.zone})` : ''}`;
|
|
69
|
+
lines.push(signedIn
|
|
70
|
+
? `Today EvoLink MCP has spent ${money(daily.used)} of its ${money(daily.limit)} daily limit; ${resets}.`
|
|
71
|
+
: `Today this API key has spent ${money(daily.used)} of its ${money(daily.limit)} daily limit; ${resets}.`);
|
|
72
|
+
if (daily.left < LOW_BALANCE_CREDITS)
|
|
73
|
+
lines.push(`Today's limit is ${daily.left <= 0 ? 'used up' : 'nearly used up'} (${money(daily.left)} left).`);
|
|
74
|
+
Object.assign(structured, {
|
|
75
|
+
daily_limit_credits: daily.limit,
|
|
76
|
+
daily_used_credits: daily.used,
|
|
77
|
+
daily_left_credits: daily.left,
|
|
78
|
+
...(daily.zone ? { reset_timezone: daily.zone } : {}),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (balance < LOW_BALANCE_CREDITS)
|
|
82
|
+
lines.push('The account balance is low; paid generations may be refused.');
|
|
83
|
+
lines.push(`Top up: ${trackedLink(TOP_UP_URL, 'top_up')}`);
|
|
84
|
+
return ok(lines.join('\n'), structured);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
return errorResult(error);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { modelParamsMeta } from '../data/model-params.js';
|
|
5
|
+
import { loadCatalog } from '../services/model-catalog.js';
|
|
6
|
+
import { referenceInputs } from '../services/model-capabilities.js';
|
|
7
|
+
import { modelPreference } from '../services/model-recommendations.js';
|
|
8
|
+
import { startingPrice } from '../services/pricing-client.js';
|
|
9
|
+
import { trackedLink } from '../services/utm.js';
|
|
10
|
+
import { modelTitle, scoreModel } from './search-models.js';
|
|
11
|
+
import { READ_ONLY, errorResult, ok } from './shared.js';
|
|
12
|
+
export function registerDiscovery(server, config) {
|
|
13
|
+
server.registerTool('recommend_models', {
|
|
14
|
+
title: 'Compare suitable models',
|
|
15
|
+
description: 'Find available documented models by output type, optional search keywords and required reference media. Returns alternatives and explicit selection reasons. Platform preferences are editorial, not a quality, popularity or release-date ranking. Starting unit prices are not task totals or budget guarantees. Read get_model and estimate_cost before any paid generation.',
|
|
16
|
+
inputSchema: {
|
|
17
|
+
type: z.enum(['image', 'video', 'audio']),
|
|
18
|
+
query: z.string().max(100).optional().describe('Search keywords, not a full generation prompt; every term must match.'),
|
|
19
|
+
references: z.array(z.enum(['image', 'video', 'audio'])).max(3).default([]).describe('Reference kinds that must have documented input fields.'),
|
|
20
|
+
limit: z.number().int().min(1).max(10).default(3),
|
|
21
|
+
},
|
|
22
|
+
annotations: { title: 'Compare suitable models', ...READ_ONLY },
|
|
23
|
+
}, async ({ type, query, references, limit }) => {
|
|
24
|
+
try {
|
|
25
|
+
const catalog = await loadCatalog(config);
|
|
26
|
+
const terms = (query ?? '').toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
27
|
+
const candidates = catalog.entries.filter(entry => entry.kind === type && entry.spec)
|
|
28
|
+
.map(entry => ({ entry, score: scoreModel(entry, terms), fields: referenceInputs(entry.spec), preference: modelPreference(entry) }))
|
|
29
|
+
.filter(item => item.score !== undefined && references.every(kind => item.fields.some(field => field.kind === kind)))
|
|
30
|
+
.sort((a, b) => b.score - a.score || (a.preference?.priority ?? Infinity) - (b.preference?.priority ?? Infinity) || a.entry.id.localeCompare(b.entry.id));
|
|
31
|
+
const models = candidates.slice(0, limit).map(({ entry, fields, preference, score }) => ({
|
|
32
|
+
model: entry.id, type: entry.kind, title: modelTitle(entry), reference_inputs: fields,
|
|
33
|
+
reasons: ['Currently available in this catalog', 'Input parameters documented',
|
|
34
|
+
...(references.length ? [`Documented reference inputs for: ${references.join(', ')}`] : []),
|
|
35
|
+
...(preference ? [`Platform preference for ${preference.use_case}`] : [])],
|
|
36
|
+
selection: { keyword_score: score, platform_preference: preference?.basis },
|
|
37
|
+
starting_price: entry.priced ? startingPrice(entry.priced) : undefined,
|
|
38
|
+
docs: trackedLink(entry.spec.docs, 'model_docs'),
|
|
39
|
+
}));
|
|
40
|
+
const next = models.length ? 'Compare parameters with get_model, then estimate_cost using the actual input. Ask for approval before generating.'
|
|
41
|
+
: 'No documented model met all filters. Try broader keywords with search_models; do not silently drop a required reference kind.';
|
|
42
|
+
return ok([`${models.length} alternatives (${candidates.length} suitable documented models).`,
|
|
43
|
+
...models.map(model => `- ${model.model}: ${model.reasons.join('; ')}`), next].join('\n'), {
|
|
44
|
+
models, total_matches: candidates.length, selection_basis: 'documented_inputs_keyword_match_platform_preference',
|
|
45
|
+
parameters_source: modelParamsMeta(), unit_prices_are_task_quotes: false, next_step: next,
|
|
46
|
+
...(catalog.pricingWarning ? { pricing_warning: catalog.pricingWarning } : {}),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
return errorResult(error);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
server.registerTool('search_docs', {
|
|
54
|
+
title: 'Search model reference documentation',
|
|
55
|
+
description: 'Search bundled official model reference titles, IDs and parameter descriptions for currently available models. Free. Returns source commit, matching parameter excerpts and official links. This is a versioned reference index, not a live full-site crawl or account/billing documentation search.',
|
|
56
|
+
inputSchema: {
|
|
57
|
+
query: z.string().trim().min(1).max(100),
|
|
58
|
+
type: z.enum(['image', 'video', 'audio', 'all']).default('all'),
|
|
59
|
+
limit: z.number().int().min(1).max(20).default(5),
|
|
60
|
+
},
|
|
61
|
+
annotations: { title: 'Search model reference documentation', ...READ_ONLY },
|
|
62
|
+
}, async ({ query, type, limit }) => {
|
|
63
|
+
try {
|
|
64
|
+
const catalog = await loadCatalog(config);
|
|
65
|
+
const terms = query.toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
66
|
+
const hits = catalog.entries.filter(entry => entry.spec && (type === 'all' || type === entry.kind))
|
|
67
|
+
.map(entry => {
|
|
68
|
+
const parameters = Object.entries(entry.spec.params);
|
|
69
|
+
const text = [entry.id, ...(entry.aliases ?? []), entry.spec.title, ...parameters.flatMap(([name, value]) => [name, value.description ?? ''])].join(' ').toLowerCase();
|
|
70
|
+
const matched = parameters.filter(([name, value]) => terms.some(term => `${name} ${value.description ?? ''}`.toLowerCase().includes(term)));
|
|
71
|
+
return { entry, matches: terms.every(term => text.includes(term)), matched };
|
|
72
|
+
}).filter(item => item.matches).sort((a, b) => b.matched.length - a.matched.length || a.entry.id.localeCompare(b.entry.id));
|
|
73
|
+
const documents = hits.slice(0, limit).map(({ entry, matched }) => ({
|
|
74
|
+
model: entry.id, title: entry.spec.title, url: trackedLink(entry.spec.docs, 'model_docs'),
|
|
75
|
+
excerpts: matched.slice(0, 5).map(([parameter, value]) => ({ parameter, text: (value.description ?? `Documented ${parameter} parameter`).slice(0, 300) })),
|
|
76
|
+
}));
|
|
77
|
+
return ok([`${hits.length} model references match "${query}".`, ...documents.map(doc => `- ${doc.model}: ${doc.url}`),
|
|
78
|
+
'Use get_model for parameters and schema. References are bundled at the reported source commit.'].join('\n'), {
|
|
79
|
+
documents, total_matches: hits.length, scope: 'available_model_reference_index', source: modelParamsMeta(),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
return errorResult(error);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { getCredits } from '../services/api-client.js';
|
|
5
|
+
import { resolveModel, suggestModels } from '../services/model-catalog.js';
|
|
6
|
+
import { formatIssues, validateInput } from '../services/param-validator.js';
|
|
7
|
+
import { estimateCost, formatEstimateRange } from '../services/pricing-client.js';
|
|
8
|
+
import { API_KEYS_URL, MCP_CONSOLE_URL, MCP_KEY_NAME, TOP_UP_URL } from '../services/http-policy.js';
|
|
9
|
+
import { trackedLink } from '../services/utm.js';
|
|
10
|
+
import { currentCredentialMode } from '../request-context.js';
|
|
11
|
+
import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, READ_ONLY, dailyLimitOf, errorResult, failure, money, ok } from './shared.js';
|
|
12
|
+
export function registerEstimateCost(server, config) {
|
|
13
|
+
server.registerTool('estimate_cost', {
|
|
14
|
+
title: 'Estimate cost',
|
|
15
|
+
description: [
|
|
16
|
+
'Check a generation input and estimate what it will cost, without submitting anything. Free.',
|
|
17
|
+
'Returns whether the input is valid, the expected price range in USD and credits, what it is based on, and whether the account balance and any spending limit (the EvoLink MCP limit, or this API key\'s) cover it.',
|
|
18
|
+
'Call it before a paid generate_* call, then use the generation confirmation template in the server instructions.',
|
|
19
|
+
].join(' '),
|
|
20
|
+
inputSchema: {
|
|
21
|
+
model: z.string().min(1).max(128).describe('Model ID, e.g. "seedance-2.0-text-to-video".'),
|
|
22
|
+
input: z.record(z.unknown()).optional()
|
|
23
|
+
.describe('The input you plan to pass to the generate tool, e.g. {"prompt":"…","duration":5,"quality":"1080p"}.'),
|
|
24
|
+
media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
|
|
25
|
+
},
|
|
26
|
+
annotations: { title: 'Estimate cost', ...READ_ONLY },
|
|
27
|
+
}, async ({ model, input, media_seconds: mediaSeconds }) => {
|
|
28
|
+
try {
|
|
29
|
+
const { catalog, entry } = await resolveModel(model, config, { fresh: true, allowStale: false });
|
|
30
|
+
if (!entry) {
|
|
31
|
+
const suggestions = suggestModels(catalog, model);
|
|
32
|
+
return failure(`Unknown model "${model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs.`, { error: { category: 'not_found', param: 'model' }, suggestions });
|
|
33
|
+
}
|
|
34
|
+
const values = input ?? {};
|
|
35
|
+
const validation = entry.spec ? validateInput(entry.spec, values) : undefined;
|
|
36
|
+
const estimate = estimateCost(entry.priced, entry.kind, values, entry.spec, { mediaSeconds });
|
|
37
|
+
const lines = [`Estimate for ${entry.id} (${entry.kind}); nothing was submitted or charged.`];
|
|
38
|
+
if (!validation) {
|
|
39
|
+
lines.push('Input not checked: this model\'s parameters are not documented here.');
|
|
40
|
+
}
|
|
41
|
+
else if (validation.errors.length > 0) {
|
|
42
|
+
lines.push(`Input problems (generate_${entry.kind} would refuse this input):`, ...formatIssues(validation.errors));
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
lines.push('Input looks valid.');
|
|
46
|
+
}
|
|
47
|
+
if (validation?.warnings.length)
|
|
48
|
+
lines.push('Warnings:', ...formatIssues(validation.warnings));
|
|
49
|
+
const range = formatEstimateRange(estimate);
|
|
50
|
+
if (estimate.status === 'estimated' && range)
|
|
51
|
+
lines.push(`Estimated cost: ${range}`);
|
|
52
|
+
else if (estimate.status === 'partial' && range)
|
|
53
|
+
lines.push(`Partial estimate at published rates: ${range} (not a total or an upper bound).`);
|
|
54
|
+
else if (estimate.status === 'token_billed')
|
|
55
|
+
lines.push('Cost: billed by tokens used; it is only known after the task runs.');
|
|
56
|
+
else if (estimate.status === 'needs_input')
|
|
57
|
+
lines.push('Cost: cannot estimate yet; see the note below.');
|
|
58
|
+
else if (estimate.uncheckable_reason === 'output_duration')
|
|
59
|
+
lines.push('Cost: the output duration is unknown, so there is no total or upper bound to quote.');
|
|
60
|
+
else
|
|
61
|
+
lines.push('Cost: pricing data is unavailable in this catalog.');
|
|
62
|
+
if (estimate.basis.length)
|
|
63
|
+
lines.push('Based on:', ...estimate.basis.map(line => `- ${line}`));
|
|
64
|
+
if (estimate.possible_extras.length)
|
|
65
|
+
lines.push('May also charge:', ...estimate.possible_extras.map(line => `- ${line}`));
|
|
66
|
+
for (const note of estimate.notes)
|
|
67
|
+
lines.push(`Note: ${note}`);
|
|
68
|
+
const structured = {
|
|
69
|
+
model: entry.id,
|
|
70
|
+
type: entry.kind,
|
|
71
|
+
pricing_scope: 'public_default_group',
|
|
72
|
+
final_budget_enforced: false,
|
|
73
|
+
input_valid: validation ? validation.errors.length === 0 : null,
|
|
74
|
+
problems: validation?.errors ?? [],
|
|
75
|
+
warnings: validation?.warnings ?? [],
|
|
76
|
+
estimate,
|
|
77
|
+
};
|
|
78
|
+
try {
|
|
79
|
+
const credits = await getCredits(config, 'estimate_cost');
|
|
80
|
+
const balance = Math.max(0, credits.user.remaining_credits);
|
|
81
|
+
lines.push(`Account balance: ${money(balance)}`);
|
|
82
|
+
structured.balance_credits = balance;
|
|
83
|
+
if (estimate.status === 'estimated' && estimate.max_credits !== undefined) {
|
|
84
|
+
const enough = balance >= estimate.max_credits;
|
|
85
|
+
structured.enough_balance = enough;
|
|
86
|
+
if (!enough)
|
|
87
|
+
lines.push(`The account balance may not cover this; top up at ${trackedLink(TOP_UP_URL, 'top_up')}.`);
|
|
88
|
+
}
|
|
89
|
+
// The key's own limit is checked before the balance: warn now instead of failing on submit.
|
|
90
|
+
if (!credits.token.unlimited_credits) {
|
|
91
|
+
const signedIn = currentCredentialMode() === 'signed_in';
|
|
92
|
+
const left = Math.max(0, credits.token.remaining_credits);
|
|
93
|
+
lines.push(signedIn
|
|
94
|
+
? `EvoLink MCP limit left: ${money(left)} (shared by all connected assistants).`
|
|
95
|
+
: `This API key's limit left: ${money(left)}.`);
|
|
96
|
+
structured.limit_scope = signedIn ? 'mcp' : 'api_key';
|
|
97
|
+
structured.limit_remaining_credits = left;
|
|
98
|
+
if (estimate.status === 'estimated' && estimate.max_credits !== undefined) {
|
|
99
|
+
const enoughLimit = left >= estimate.max_credits;
|
|
100
|
+
structured.enough_limit = enoughLimit;
|
|
101
|
+
if (!enoughLimit) {
|
|
102
|
+
lines.push(signedIn
|
|
103
|
+
? `The EvoLink MCP limit may not cover this. It is a limit the user set, not the account balance; they can raise it at ${trackedLink(MCP_CONSOLE_URL, 'api_keys')} (the key named "${MCP_KEY_NAME}").`
|
|
104
|
+
: `This API key's limit may not cover this; raise it at ${trackedLink(API_KEYS_URL, 'api_keys')} or use another key.`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const daily = dailyLimitOf(credits.token);
|
|
109
|
+
if (daily && estimate.status === 'estimated' && estimate.max_credits !== undefined) {
|
|
110
|
+
const signedIn = currentCredentialMode() === 'signed_in';
|
|
111
|
+
const enoughToday = daily.left >= estimate.max_credits;
|
|
112
|
+
structured.daily_left_credits = daily.left;
|
|
113
|
+
structured.enough_daily_limit = enoughToday;
|
|
114
|
+
if (!enoughToday) {
|
|
115
|
+
const resets = `it resets at midnight${daily.zone ? ` (${daily.zone})` : ''}`;
|
|
116
|
+
lines.push(signedIn
|
|
117
|
+
? `Today's EvoLink MCP limit may not cover this (${money(daily.left)} left today; ${resets}). It is a limit the user set, not the account balance.`
|
|
118
|
+
: `Today's limit of this API key may not cover this (${money(daily.left)} left today; ${resets}).`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
lines.push('Balance: could not be read right now.');
|
|
124
|
+
}
|
|
125
|
+
if (catalog.pricingWarning) {
|
|
126
|
+
lines.push(`Note: ${catalog.pricingWarning}`);
|
|
127
|
+
structured.pricing_warning = catalog.pricingWarning;
|
|
128
|
+
}
|
|
129
|
+
lines.push('This is an estimate from published prices. The amount actually reserved is shown when the task is submitted, and the final charge when it finishes.');
|
|
130
|
+
return ok(lines.join('\n'), structured);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
return errorResult(error);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// Copyright 2024 EvoLink AI. SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Generated from Evolink-AI/evolink-mcp; adapted for direct REST operations. See platform/LICENSE and platform/NOTICE.
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { submitTask } from '../services/api-client.js';
|
|
5
|
+
import { resolveModel, suggestModels } from '../services/model-catalog.js';
|
|
6
|
+
import { formatIssues, validateInput } from '../services/param-validator.js';
|
|
7
|
+
import { estimateCost, formatEstimateRange } from '../services/pricing-client.js';
|
|
8
|
+
import { CLIENT_REQUEST_ID_PATTERN, newRunId } from '../services/http-policy.js';
|
|
9
|
+
import { formatUsd } from '../services/error-handler.js';
|
|
10
|
+
import { MEDIA_SECONDS_DESCRIPTION, MEDIA_SECONDS_MAX, PAID, errorResult, failure, money, ok, progressReporter, usdOf } from './shared.js';
|
|
11
|
+
import { RESULT_DELIVERY_GUIDANCE, TERMINAL_STATUSES, describeTask, waitForTask } from './task-format.js';
|
|
12
|
+
import { PAID_GENERATION_GUIDANCE } from '../tool-guidance.js';
|
|
13
|
+
import { currentRequestCredentials } from '../request-context.js';
|
|
14
|
+
const PATHS = {
|
|
15
|
+
image: '/v1/images/generations',
|
|
16
|
+
video: '/v1/videos/generations',
|
|
17
|
+
audio: '/v1/audios/generations',
|
|
18
|
+
};
|
|
19
|
+
/** Images usually finish in seconds, so the tool waits for them; video and audio return the task at once. */
|
|
20
|
+
const WAIT_MS = { image: 40_000, video: 0, audio: 0 };
|
|
21
|
+
const DESCRIPTIONS = {
|
|
22
|
+
image: 'Generate or edit images with an EvoLink image model. PAID: charges the user\'s EvoLink balance.',
|
|
23
|
+
video: 'Generate a video with an EvoLink video model (text-to-video, image-to-video, reference, edit, extend). PAID: charges the user\'s EvoLink balance.',
|
|
24
|
+
audio: 'Generate music, songs or speech with an EvoLink audio model. PAID: charges the user\'s EvoLink balance.',
|
|
25
|
+
};
|
|
26
|
+
const AFTER = {
|
|
27
|
+
image: 'Waits up to 40 s and returns the image links when ready; otherwise returns the task_id for get_task.',
|
|
28
|
+
video: 'Returns a task_id at once (videos take minutes); then call get_task, which can wait up to 45 s per call.',
|
|
29
|
+
audio: 'Returns a task_id at once; then call get_task, which can wait up to 45 s per call.',
|
|
30
|
+
};
|
|
31
|
+
function description(kind) {
|
|
32
|
+
return [
|
|
33
|
+
DESCRIPTIONS[kind],
|
|
34
|
+
PAID_GENERATION_GUIDANCE,
|
|
35
|
+
'Find models with search_models and their parameters with get_model; pass the parameters in input.',
|
|
36
|
+
AFTER[kind],
|
|
37
|
+
'Never call this again to check progress or to "retry" a running task: each call creates and charges a new task.',
|
|
38
|
+
'After a network error or timeout, reuse the same client_request_id to retry without being charged twice.',
|
|
39
|
+
RESULT_DELIVERY_GUIDANCE,
|
|
40
|
+
].join(' ');
|
|
41
|
+
}
|
|
42
|
+
/** Longest prompt accepted through the prompt shortcut. */
|
|
43
|
+
const PROMPT_SHORTCUT_MAX = 20_000;
|
|
44
|
+
function rangeText(estimate) {
|
|
45
|
+
return formatEstimateRange(estimate) ?? 'unknown';
|
|
46
|
+
}
|
|
47
|
+
/** Why max_cost_usd could not be checked, and what the assistant can do next. */
|
|
48
|
+
function uncheckedCap(estimate, pricingWarning) {
|
|
49
|
+
if (estimate.uncheckable_reason === 'output_duration') {
|
|
50
|
+
return ['the generated output duration is not fixed, so the declared seconds cannot establish an upper bound', 'Use an explicit duration if the model accepts it; otherwise ask the user whether to proceed without a cap.'];
|
|
51
|
+
}
|
|
52
|
+
if (estimate.uncheckable_reason === 'reference_video') {
|
|
53
|
+
return [
|
|
54
|
+
'this per-second video request uses input.video_urls, input.video_url or input.source_task_id, and published prices do not fully cover input video seconds or video-dependent billing multipliers',
|
|
55
|
+
'media_seconds cannot resolve this billing gap. Ask the user whether to proceed without a cap.',
|
|
56
|
+
];
|
|
57
|
+
}
|
|
58
|
+
if (estimate.status === 'token_billed') {
|
|
59
|
+
return ['it is billed by tokens used, so its cost is only known afterwards', 'Ask the user whether to proceed without a cap.'];
|
|
60
|
+
}
|
|
61
|
+
if (estimate.missing === 'media_seconds') {
|
|
62
|
+
return [
|
|
63
|
+
'it is billed per second and has no duration parameter, so EvoLink measures the seconds when the task runs (usually the length of the input video or audio)',
|
|
64
|
+
'If you know that length, pass it as media_seconds; otherwise ask the user whether to proceed without a cap.',
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
if (estimate.missing === 'duration') {
|
|
68
|
+
return ['it is billed per second and input.duration is not set', 'Set input.duration, or ask the user whether to proceed without a cap.'];
|
|
69
|
+
}
|
|
70
|
+
// Notes end with a full stop; the sentence around the reason adds its own.
|
|
71
|
+
const note = estimate.notes[0] ?? pricingWarning ?? 'no price could be found for it';
|
|
72
|
+
return [note.replace(/[.\s]+$/, ''), 'Ask the user whether to proceed without a cap.'];
|
|
73
|
+
}
|
|
74
|
+
export function registerGenerateTools(server, config) {
|
|
75
|
+
for (const kind of ['image', 'video', 'audio'])
|
|
76
|
+
registerGenerate(server, config, kind);
|
|
77
|
+
}
|
|
78
|
+
function registerGenerate(server, config, kind) {
|
|
79
|
+
const name = `generate_${kind}`;
|
|
80
|
+
const title = `Generate ${kind} (paid)`;
|
|
81
|
+
server.registerTool(name, {
|
|
82
|
+
title,
|
|
83
|
+
description: description(kind),
|
|
84
|
+
inputSchema: {
|
|
85
|
+
model: z.string().min(1).max(128).describe(`${kind[0].toUpperCase()}${kind.slice(1)} model ID from search_models.`),
|
|
86
|
+
// The cap is checked in the handler: a schema limit makes the SDK answer with a bare validation error.
|
|
87
|
+
prompt: z.string().optional().describe(`Shortcut for input.prompt; up to ${PROMPT_SHORTCUT_MAX.toLocaleString('en-US')} characters (get_model lists the model's own limit).`),
|
|
88
|
+
input: z.record(z.unknown()).optional()
|
|
89
|
+
.describe('Model parameters exactly as listed by get_model, e.g. {"prompt":"…","quality":"1080p"}. Do not put model or callback_url here.'),
|
|
90
|
+
client_request_id: z.string().regex(CLIENT_REQUEST_ID_PATTERN).optional()
|
|
91
|
+
.describe('Optional idempotency key (16–96 characters: letters, digits, . _ -). Reuse the same value only to retry the same request after a network error or timeout.'),
|
|
92
|
+
max_cost_usd: z.number().positive().max(10_000).optional()
|
|
93
|
+
.describe('Optional estimate-based submission cap, not a final settlement guarantee: refuses to submit when fresh public prices are unavailable, the estimate is higher or published rules cannot cover the full request. Per-second video requests with video_urls, video_url or source_task_id cannot use this cap, even with media_seconds.'),
|
|
94
|
+
media_seconds: z.number().positive().max(MEDIA_SECONDS_MAX).optional().describe(MEDIA_SECONDS_DESCRIPTION),
|
|
95
|
+
},
|
|
96
|
+
annotations: { title, ...PAID },
|
|
97
|
+
}, async (args, extra) => {
|
|
98
|
+
const started = Date.now();
|
|
99
|
+
const credentials = currentRequestCredentials();
|
|
100
|
+
const unavailable = !credentials?.serviceChannel && !credentials?.apiKey ? credentials?.unavailableReason : undefined;
|
|
101
|
+
if (unavailable)
|
|
102
|
+
return failure(`${unavailable} Nothing was submitted or charged.`, {
|
|
103
|
+
error: { category: 'unauthorized' }, charged: 'no',
|
|
104
|
+
});
|
|
105
|
+
const input = { ...(args.input ?? {}) };
|
|
106
|
+
if (args.prompt !== undefined) {
|
|
107
|
+
if (input.prompt !== undefined && input.prompt !== args.prompt) {
|
|
108
|
+
return failure('prompt was given twice with different values (prompt and input.prompt). Pass it once. Nothing was submitted or charged.', {
|
|
109
|
+
error: { category: 'invalid_request', param: 'prompt' },
|
|
110
|
+
charged: 'no',
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
if (args.prompt.length > PROMPT_SHORTCUT_MAX) {
|
|
114
|
+
return failure(`The prompt is ${args.prompt.length.toLocaleString('en-US')} characters; the limit is ${PROMPT_SHORTCUT_MAX.toLocaleString('en-US')}. Shorten it and try again. Nothing was submitted or charged.`, {
|
|
115
|
+
error: { category: 'invalid_request', param: 'prompt' },
|
|
116
|
+
charged: 'no',
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
input.prompt = args.prompt;
|
|
120
|
+
}
|
|
121
|
+
let clientRequestId;
|
|
122
|
+
let acceptedTaskId;
|
|
123
|
+
try {
|
|
124
|
+
const { catalog, entry } = await resolveModel(args.model, config, { fresh: true, allowStale: false });
|
|
125
|
+
if (!entry) {
|
|
126
|
+
const suggestions = suggestModels(catalog, args.model, kind);
|
|
127
|
+
return failure(`Unknown ${kind} model "${args.model}".${suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : ''} Use search_models to find model IDs. Nothing was submitted or charged.`, { error: { category: 'not_found', param: 'model' }, suggestions, charged: 'no' });
|
|
128
|
+
}
|
|
129
|
+
if (entry.kind !== kind) {
|
|
130
|
+
return failure(`${entry.id} is ${entry.kind === 'video' ? 'a' : 'an'} ${entry.kind} model; use generate_${entry.kind}. Nothing was submitted or charged.`, {
|
|
131
|
+
error: { category: 'invalid_request', param: 'model' },
|
|
132
|
+
use_tool: `generate_${entry.kind}`,
|
|
133
|
+
charged: 'no',
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
const warnings = [];
|
|
137
|
+
if (entry.spec) {
|
|
138
|
+
const validation = validateInput(entry.spec, input);
|
|
139
|
+
if (validation.errors.length > 0) {
|
|
140
|
+
return failure([
|
|
141
|
+
`The input for ${entry.id} has problems; nothing was submitted or charged:`,
|
|
142
|
+
...formatIssues(validation.errors),
|
|
143
|
+
'get_model lists every parameter with its allowed values.',
|
|
144
|
+
].join('\n'), { error: { category: 'invalid_request' }, problems: validation.errors, charged: 'no' });
|
|
145
|
+
}
|
|
146
|
+
warnings.push(...validation.warnings.map(issue => `${issue.param} ${issue.problem}`));
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
warnings.push('This model\'s parameters are not documented here, so the input was not checked before sending.');
|
|
150
|
+
}
|
|
151
|
+
// media_seconds only prices the request; the body below is built from input alone.
|
|
152
|
+
const estimate = estimateCost(entry.priced, kind, input, entry.spec, { mediaSeconds: args.media_seconds });
|
|
153
|
+
if (args.max_cost_usd !== undefined) {
|
|
154
|
+
if (estimate.uncheckable_reason !== undefined || estimate.status !== 'estimated' || estimate.max_usd === undefined) {
|
|
155
|
+
const [reason, next] = uncheckedCap(estimate, catalog.pricingWarning);
|
|
156
|
+
return failure(`max_cost_usd cannot be checked for ${entry.id}: ${reason}. Nothing was submitted or charged. ${next}`, {
|
|
157
|
+
error: { category: 'invalid_request', param: 'max_cost_usd' },
|
|
158
|
+
estimate,
|
|
159
|
+
charged: 'no',
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
if (estimate.max_usd > args.max_cost_usd) {
|
|
163
|
+
return failure(`The estimated cost ${rangeText(estimate)} is above max_cost_usd $${formatUsd(args.max_cost_usd)}. Nothing was submitted or charged. Lower the duration, count or quality, or ask the user to raise the cap.`, {
|
|
164
|
+
error: { category: 'invalid_request', param: 'max_cost_usd' },
|
|
165
|
+
estimate,
|
|
166
|
+
charged: 'no',
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
clientRequestId = args.client_request_id ?? newRunId();
|
|
171
|
+
const body = { ...input, model: entry.id };
|
|
172
|
+
const submitted = await submitTask(config, {
|
|
173
|
+
path: entry.spec?.path ?? PATHS[kind],
|
|
174
|
+
body,
|
|
175
|
+
tool: name,
|
|
176
|
+
idempotencyKey: clientRequestId,
|
|
177
|
+
});
|
|
178
|
+
acceptedTaskId = submitted.id;
|
|
179
|
+
let task = submitted;
|
|
180
|
+
const waitUntil = started + WAIT_MS[kind];
|
|
181
|
+
if (!TERMINAL_STATUSES.has(task.status) && WAIT_MS[kind] > 0 && Date.now() + 3_000 < waitUntil) {
|
|
182
|
+
const report = progressReporter(extra, WAIT_MS[kind] / 1000);
|
|
183
|
+
try {
|
|
184
|
+
task = await waitForTask(config, submitted.id, {
|
|
185
|
+
deadline: waitUntil,
|
|
186
|
+
tool: name,
|
|
187
|
+
signal: extra.signal,
|
|
188
|
+
onPoll: current => report((Date.now() - started) / 1000, `${current.status}, ${current.progress ?? 0}%`),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// The task exists; a failed status read must not turn a successful submit into an error.
|
|
193
|
+
task = submitted;
|
|
194
|
+
}
|
|
195
|
+
task.usage = { ...submitted.usage, ...task.usage };
|
|
196
|
+
}
|
|
197
|
+
const view = describeTask({ ...task, request_id: task.request_id ?? submitted.request_id });
|
|
198
|
+
const header = submitted.idempotency_replayed
|
|
199
|
+
? `This client_request_id was used before: returning the original task (no new charge).`
|
|
200
|
+
: `Submitted ${entry.id}.`;
|
|
201
|
+
const lines = [header, ...view.lines];
|
|
202
|
+
const reserved = submitted.usage?.credits_reserved;
|
|
203
|
+
if (typeof reserved === 'number' && reserved > 0 && !lines.some(line => line.startsWith('Reserved:')) && task.status !== 'completed') {
|
|
204
|
+
lines.push(`Reserved: ${money(reserved)}`);
|
|
205
|
+
}
|
|
206
|
+
if (estimate.status === 'estimated')
|
|
207
|
+
lines.push(`Estimate before submitting: ${rangeText(estimate)}`);
|
|
208
|
+
if (estimate.status === 'partial') {
|
|
209
|
+
lines.push(`Partial estimate at published rates: ${rangeText(estimate)} (not a total or an upper bound).`);
|
|
210
|
+
for (const extra of estimate.possible_extras)
|
|
211
|
+
lines.push(`May also charge: ${extra}`);
|
|
212
|
+
for (const note of estimate.notes)
|
|
213
|
+
lines.push(`Note: ${note}`);
|
|
214
|
+
}
|
|
215
|
+
for (const warning of warnings)
|
|
216
|
+
lines.push(`Warning: ${warning}`);
|
|
217
|
+
lines.push(`client_request_id: ${clientRequestId}`);
|
|
218
|
+
return ok(lines.join('\n'), {
|
|
219
|
+
...view.structured,
|
|
220
|
+
submitted: { model: entry.id, input },
|
|
221
|
+
pricing_scope: 'public_default_group',
|
|
222
|
+
final_budget_enforced: false,
|
|
223
|
+
client_request_id: clientRequestId,
|
|
224
|
+
replayed: submitted.idempotency_replayed === true,
|
|
225
|
+
...(typeof reserved === 'number' ? { reserved_credits: reserved, reserved_usd: usdOf(reserved) } : {}),
|
|
226
|
+
...(estimate.status === 'estimated' ? { estimate: { min_usd: estimate.min_usd, max_usd: estimate.max_usd } } : {}),
|
|
227
|
+
...(estimate.status === 'partial' ? { estimate } : {}),
|
|
228
|
+
...(warnings.length ? { warnings } : {}),
|
|
229
|
+
}, view.resources);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
// clientRequestId is set right before the submit, so it also tells whether a request may have gone out.
|
|
233
|
+
return errorResult(error, { paid: clientRequestId !== undefined, clientRequestId, taskId: acceptedTaskId,
|
|
234
|
+
phase: acceptedTaskId ? 'accepted' : clientRequestId ? 'submit_started' : 'before_submit' });
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
}
|