@imazeo/mcp 0.0.0-stage → 1.0.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.
@@ -0,0 +1,181 @@
1
+ import { z } from 'zod';
2
+ export const id = z.uuidv4();
3
+ export const pathInput = z.string().min(1).max(500)
4
+ .describe('File path relative to IMAZEO_INPUT_DIR. Use forward slashes.');
5
+ export const output = z.string().min(1).max(120)
6
+ .describe('New filename, including the media extension, under IMAZEO_OUTPUT_DIR.');
7
+ export const confirmation = z.literal(true)
8
+ .describe('Set only after the user authorizes this action and the associated data transfer.');
9
+ export const idempotencyKey = id.describe('Caller-generated UUID v4. Retain it for recovery of this exact request.');
10
+ export const processing = {
11
+ quoteId: id.describe('Unexpired quote for the same operation, units and remote setting.'),
12
+ idempotencyKey,
13
+ confirm: confirmation,
14
+ };
15
+ export const quoteKinds = [
16
+ 'code.qr', 'code.barcode', 'pdf.info', 'pdf.render', 'pdf.merge', 'pdf.extract',
17
+ 'image.transform', 'docx.render', 'xlsx.render', 'pptx.render', 'website.capture',
18
+ ];
19
+ export const pagination = {
20
+ page: z.int().min(1).optional(),
21
+ limit: z.int().min(1).max(100).optional(),
22
+ };
23
+ export const httpUrl = z.url({ protocol: /^https?$/ }).max(2048)
24
+ .refine((value) => {
25
+ const url = URL.parse(value);
26
+ return url !== null && !url.username && !url.password;
27
+ }, 'Embedded URL credentials are unsupported.')
28
+ .describe('Public HTTP(S) URL without embedded credentials.');
29
+ export const rasterFormat = z.enum(['png', 'jpeg', 'webp']);
30
+ const color = z.string().regex(/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i);
31
+ const rasterQuality = z.int().min(1).max(100);
32
+ const dimension = z.int().min(1).max(10000);
33
+ const padding = z.int().min(0).max(10000);
34
+ const codeStyle = {
35
+ format: z.enum(['png', 'svg']).optional(),
36
+ foreground: color.optional(),
37
+ background: color.optional(),
38
+ transparent: z.boolean().optional(),
39
+ };
40
+ export const qrOptions = z.strictObject({
41
+ content: z.string().min(1).max(2048).refine((value) => Buffer.byteLength(value) <= 2048),
42
+ ...codeStyle,
43
+ size: z.int().min(128).max(1024).optional(),
44
+ margin: z.int().min(0).max(16).optional(),
45
+ errorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional(),
46
+ });
47
+ export const barcodeOptions = z.strictObject({
48
+ type: z.enum(['code128', 'code39', 'ean13', 'ean8', 'upca', 'itf14']),
49
+ content: z.string().min(1).max(80).describe('Barcode payload as text. Preserve leading zeroes.'),
50
+ ...codeStyle,
51
+ scale: z.int().min(1).max(6).optional(),
52
+ height: z.int().min(4).max(40).optional(),
53
+ includeText: z.boolean().optional(),
54
+ });
55
+ export const transformOptions = z.strictObject({
56
+ width: dimension.optional(),
57
+ height: dimension.optional(),
58
+ fit: z.enum(['cover', 'contain', 'inside', 'fill']).optional(),
59
+ crop: z.strictObject({
60
+ left: z.int().min(0).max(25000000), top: z.int().min(0).max(25000000),
61
+ width: dimension, height: dimension,
62
+ }).optional(),
63
+ format: z.enum(['jpeg', 'png', 'webp', 'avif', 'gif']).optional(),
64
+ quality: rasterQuality.optional(),
65
+ rotate: z.literal([-360, -270, -180, -90, 0, 90, 180, 270, 360]).optional(),
66
+ flip: z.boolean().optional(),
67
+ flop: z.boolean().optional(),
68
+ optimize: z.boolean().optional(),
69
+ stripMetadata: z.literal(true).optional(),
70
+ grayscale: z.boolean().optional(),
71
+ negate: z.boolean().optional(),
72
+ blur: z.number().min(0.3).max(10).optional(),
73
+ sharpen: z.number().min(0.5).max(5).optional(),
74
+ brightness: z.number().min(0).max(3).optional(),
75
+ saturation: z.number().min(0).max(3).optional(),
76
+ hue: z.int().min(-180).max(180).optional(),
77
+ trim: z.union([z.literal(true), z.strictObject({ threshold: rasterQuality })]).optional(),
78
+ extend: z.strictObject({ top: padding, right: padding, bottom: padding, left: padding }).optional(),
79
+ background: color.optional(),
80
+ position: z.enum(['center', 'entropy', 'attention']).optional(),
81
+ }).refine(({ fit, width, height }) => !fit || fit === 'inside' || (width && height), 'The selected fit requires width and height.');
82
+ const pageNumber = z.int().min(1).max(100);
83
+ const pages = z.strictObject({
84
+ mode: z.literal('pages'),
85
+ pages: z.array(pageNumber).min(1).max(100)
86
+ .refine((values) => new Set(values).size === values.length, 'Page numbers must be unique.'),
87
+ });
88
+ const range = z.strictObject({
89
+ mode: z.literal('range'),
90
+ start: pageNumber,
91
+ end: pageNumber,
92
+ }).refine(({ start, end }) => end >= start, 'Page range end must be at or after its start.');
93
+ export const pdfSelection = z.discriminatedUnion('mode', [pages, range]);
94
+ export function pdfQuery(selection) {
95
+ if (selection?.mode === 'pages')
96
+ return { pages: selection.pages.join(',') };
97
+ if (selection?.mode === 'range')
98
+ return { rangeStart: selection.start, rangeEnd: selection.end };
99
+ return {};
100
+ }
101
+ export function renderPages(selection) {
102
+ if (selection?.mode === 'pages')
103
+ return selection.pages;
104
+ if (selection?.mode === 'range') {
105
+ return Array.from({ length: selection.end - selection.start + 1 }, (_, i) => i + selection.start);
106
+ }
107
+ return [1];
108
+ }
109
+ export const conversionEngines = z.enum(['docx', 'xlsx', 'pptx', 'website']);
110
+ const conversionStyle = {
111
+ page: z.int().min(1).max(50).optional(),
112
+ scale: z.number().min(0.1).max(6).optional(),
113
+ format: rasterFormat.optional(),
114
+ quality: rasterQuality.optional(),
115
+ };
116
+ export const conversion = z.discriminatedUnion('engine', [
117
+ z.strictObject({
118
+ engine: z.literal('docx'),
119
+ input: pathInput,
120
+ options: z.strictObject({
121
+ ...conversionStyle,
122
+ fitSinglePage: z.boolean().optional(),
123
+ honorWordPageBreaks: z.boolean().optional(),
124
+ renderHeaders: z.boolean().optional(),
125
+ renderFooters: z.boolean().optional(),
126
+ renderFootnotes: z.boolean().optional(),
127
+ renderEndnotes: z.boolean().optional(),
128
+ repairBrokenRelationships: z.boolean().optional(),
129
+ unwrapSdt: z.boolean().optional(),
130
+ collapseMcAlternate: z.boolean().optional(),
131
+ ignoreImageWrap: z.boolean().optional(),
132
+ ignoreTableWrap: z.boolean().optional(),
133
+ applyWordChrome: z.boolean().optional(),
134
+ normalizeTheme: z.boolean().optional(),
135
+ renderChanges: z.boolean().optional(),
136
+ }).optional(),
137
+ }),
138
+ z.strictObject({
139
+ engine: z.literal('xlsx'),
140
+ input: pathInput,
141
+ options: z.strictObject({
142
+ ...conversionStyle,
143
+ sheet: z.int().min(1).max(50).optional(),
144
+ renderMode: z.enum(['sheet', 'print']).optional(),
145
+ range: z.string().max(40).optional(),
146
+ showGridLines: z.boolean().optional(),
147
+ paperSize: z.enum(['saved', 'A3', 'A4', 'A5', 'Letter', 'Legal', 'Tabloid', 'B5']).optional(),
148
+ }).optional(),
149
+ }),
150
+ z.strictObject({
151
+ engine: z.literal('pptx'),
152
+ input: pathInput,
153
+ options: z.strictObject(conversionStyle).optional(),
154
+ }),
155
+ z.strictObject({
156
+ engine: z.literal('website'),
157
+ url: httpUrl,
158
+ options: z.strictObject({
159
+ scale: conversionStyle.scale,
160
+ format: conversionStyle.format,
161
+ quality: conversionStyle.quality,
162
+ mode: z.enum(['viewport', 'fullPage', 'element', 'clip']).optional(),
163
+ width: z.int().min(240).max(3840).optional(),
164
+ height: z.int().min(240).max(2160).optional(),
165
+ selector: z.string().max(200).optional(),
166
+ clipX: z.int().min(0).max(30000).optional(),
167
+ clipY: z.int().min(0).max(30000).optional(),
168
+ clipWidth: z.int().min(1).max(3840).optional(),
169
+ clipHeight: z.int().min(1).max(16000).optional(),
170
+ javascriptEnabled: z.boolean().optional(),
171
+ blockTrackers: z.boolean().optional(),
172
+ autoScroll: z.boolean().optional(),
173
+ freezeAnimations: z.boolean().optional(),
174
+ omitBackground: z.boolean().optional(),
175
+ colorScheme: z.enum(['light', 'dark']).optional(),
176
+ reducedMotion: z.boolean().optional(),
177
+ waitUntil: z.enum(['load', 'domcontentloaded', 'networkidle2']).optional(),
178
+ waitMs: z.int().min(0).max(3000).optional(),
179
+ }).refine(({ mode, selector }) => mode !== 'element' || Boolean(selector?.trim()), 'Element mode requires a selector.').optional(),
180
+ }),
181
+ ]);
package/dist/server.js ADDED
@@ -0,0 +1,95 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { z } from 'zod';
3
+ import { createApi, REQUEST_TIMEOUT_MS } from './api.js';
4
+ import { describeError } from './errors.js';
5
+ import { registerMedia } from './tools/media.js';
6
+ import { registerProject } from './tools/project.js';
7
+ export const identity = { name: 'com.imazeo/media', title: 'Imazeo Media', version: '1.0.1' };
8
+ const annotations = {
9
+ read: { readOnlyHint: true, openWorldHint: true },
10
+ download: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
11
+ idempotent: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
12
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
13
+ destructive: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
14
+ };
15
+ function reply(api, data, isError = false) {
16
+ const text = api.redact(JSON.stringify(data, (_key, value) => typeof value === 'string' ? api.redact(value) : value));
17
+ if (Buffer.byteLength(text) > 512 * 1024) {
18
+ const error = { code: 'RESULT_TOO_LARGE', message: 'Request a smaller result, such as a shorter list or date range.' };
19
+ return { isError: true, structuredContent: error, content: [{ type: 'text', text: JSON.stringify(error) }] };
20
+ }
21
+ const structuredContent = JSON.parse(text);
22
+ return { ...(isError ? { isError: true } : {}), structuredContent, content: [{ type: 'text', text }] };
23
+ }
24
+ export function createServer(options) {
25
+ const api = createApi(options.key, options.fetch);
26
+ const server = new McpServer(identity, {
27
+ instructions: 'Tools access the Imazeo project bound to the configured API key. ' +
28
+ 'Obtain a quote and user approval before spending processing credits. ' +
29
+ 'Ask before transmitting local files or changing project state. ' +
30
+ 'Retain idempotency keys. After an uncertain outcome, check the operation or conversion before considering another submission. ' +
31
+ 'Local output tools return filenames and metadata.',
32
+ });
33
+ let active = 0;
34
+ const register = (name, description, schema, effect, action) => {
35
+ // Advertise the schema but own runtime validation so validation messages
36
+ // cannot echo arbitrary property names or rejected values into the client.
37
+ const jsonSchema = z.toJSONSchema(schema, { io: 'input', target: 'draft-07' });
38
+ const inputSchema = z.looseObject({});
39
+ const advertised = {
40
+ ...inputSchema['~standard'],
41
+ jsonSchema: { input: () => jsonSchema, output: () => jsonSchema },
42
+ };
43
+ server.registerTool('imazeo_' + name, {
44
+ description,
45
+ inputSchema: { '~standard': advertised },
46
+ annotations: annotations[effect],
47
+ }, async (input, ctx) => {
48
+ if (active >= 2)
49
+ return reply(api, { code: 'SERVER_BUSY', message: 'Wait for a current Imazeo call to finish.' }, true);
50
+ if (api.containsSecret(JSON.stringify(input))) {
51
+ return reply(api, { code: 'INVALID_INPUT', message: 'Keep the project key in the server configuration.' }, true);
52
+ }
53
+ const validated = schema.safeParse(input);
54
+ if (!validated.success) {
55
+ return reply(api, { code: 'INVALID_INPUT', message: 'Check the tool input against its published schema.' }, true);
56
+ }
57
+ const signal = AbortSignal.any([ctx.mcpReq.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
58
+ const scope = { signal };
59
+ active += 1;
60
+ try {
61
+ signal.throwIfAborted();
62
+ const result = await api.run(scope, () => action(validated.data, { api, files: options.files, signal }));
63
+ return reply(api, {
64
+ ...result,
65
+ ...(scope.requestId ? { requestId: scope.requestId } : {}),
66
+ ...(scope.operationId ? { operationId: scope.operationId } : {}),
67
+ }, 'complete' in result && result.complete === false);
68
+ }
69
+ catch (error) {
70
+ const described = describeError(error, signal);
71
+ const uncertain = scope.mutationSent && !scope.mutationAccepted &&
72
+ (!scope.status || scope.status >= 500);
73
+ return reply(api, {
74
+ ...described,
75
+ ...(scope.requestId ? { requestId: scope.requestId } : {}),
76
+ ...(scope.operationId ? { operationId: scope.operationId } : {}),
77
+ ...(scope.retryAfter ? { retryAfter: scope.retryAfter } : {}),
78
+ ...(scope.mutationAccepted ? {
79
+ remoteAccepted: true,
80
+ recovery: 'Imazeo accepted the request. Check its operation, job, or project listing before submitting again.',
81
+ } : uncertain ? {
82
+ outcomeUnknown: true,
83
+ recovery: 'Check the operation, job, or project listing before submitting again.',
84
+ } : {}),
85
+ }, true);
86
+ }
87
+ finally {
88
+ active -= 1;
89
+ }
90
+ });
91
+ };
92
+ registerMedia(register);
93
+ registerProject(register);
94
+ return server;
95
+ }
@@ -0,0 +1,160 @@
1
+ import { z } from 'zod';
2
+ import { ToolError } from '../errors.js';
3
+ import { imageTypes, documentTypes, pdfPages } from '../files.js';
4
+ import { barcodeOptions, confirmation, httpUrl, id, output, pathInput, pdfQuery, pdfSelection, processing, qrOptions, rasterFormat, renderPages, transformOptions, } from '../schemas.js';
5
+ const pdf = { '.pdf': documentTypes['.pdf'] };
6
+ const codeMime = (format) => format === 'svg' ? 'image/svg+xml' : 'image/png';
7
+ const previewTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' };
8
+ const codeTypes = { '.png': 'image/png', '.svg': 'image/svg+xml' };
9
+ const artifactTypes = {
10
+ qr: codeTypes, barcode: codeTypes, pdf_render: previewTypes,
11
+ pdf_merge: pdf, pdf_extract: pdf, image_transform: imageTypes,
12
+ };
13
+ function binaryMetadata(result) {
14
+ return {
15
+ contentType: result.contentType,
16
+ transformationId: result.transformationId,
17
+ cache: result.cache,
18
+ };
19
+ }
20
+ export async function saveResult(result, name, ctx) {
21
+ if ('data' in result) {
22
+ if (!name)
23
+ throw new ToolError('OUTPUT_REQUIRED', 'Specify an output filename to save this binary result.');
24
+ return {
25
+ ...await ctx.files.save(name, [{ ...result, pageNumber: result.pdfPage }], ctx.signal),
26
+ ...binaryMetadata(result),
27
+ };
28
+ }
29
+ if ('pages' in result && !('pageCount' in result)) {
30
+ if (!name)
31
+ throw new ToolError('OUTPUT_REQUIRED', 'Specify an output filename to save rendered pages.');
32
+ return ctx.files.save(name, pdfPages(result.pages), ctx.signal);
33
+ }
34
+ if ('pageCount' in result)
35
+ return { info: result };
36
+ throw new ToolError('INVALID_RESULT', 'Imazeo returned an unexpected processing result.');
37
+ }
38
+ export function registerMedia(register) {
39
+ register('upload_image', 'Send a local image to Imazeo and create a private stored original. Uses project storage. Confirm the upload.', z.strictObject({ input: pathInput, confirm: confirmation }), 'create', async ({ input }, { api, files, signal }) => {
40
+ const [file] = await files.readMany([input], { ...imageTypes, '.svg': 'image/svg+xml' }, signal);
41
+ return { image: await (await api.project()).images.upload(file, { signal }) };
42
+ });
43
+ register('transform_image', 'Resize, convert, or edit an owned Imazeo image or public remote image. Sends the request to Imazeo and may spend credits. Remote sources require a remote image.transform quote.', z.strictObject({
44
+ source: z.discriminatedUnion('type', [
45
+ z.strictObject({ type: z.literal('original'), imageId: id }),
46
+ z.strictObject({ type: z.literal('url'), url: httpUrl }),
47
+ ]),
48
+ transform: transformOptions.optional(),
49
+ mode: z.enum(['PERSIST', 'CACHE', 'EPHEMERAL']).optional(),
50
+ maxOutputBytes: z.int().min(1).max(64 * 1024 * 1024).optional(),
51
+ output,
52
+ ...processing,
53
+ }), 'create', async ({ source, transform, mode, maxOutputBytes, output, quoteId, idempotencyKey }, ctx) => {
54
+ const format = transform?.format ?? 'webp';
55
+ await ctx.files.prepare(output, 'image/' + format);
56
+ const sourceOptions = source.type === 'original' ? { imageId: source.imageId } : { url: source.url };
57
+ const result = await (await ctx.api.project()).transforms.create({ ...sourceOptions, transform, mode, maxOutputBytes }, ctx.signal, { quoteId, idempotencyKey });
58
+ return saveResult(result, output, ctx);
59
+ });
60
+ register('generate_qr', 'Send text or a URL to Imazeo for static QR generation. May spend credits. Saves PNG or SVG locally.', z.strictObject({ options: qrOptions, output, ...processing }), 'create', async ({ options, output, quoteId, idempotencyKey }, ctx) => {
61
+ await ctx.files.prepare(output, codeMime(options.format));
62
+ const result = await (await ctx.api.project()).qr.generate(options, ctx.signal, { quoteId, idempotencyKey });
63
+ return saveResult(result, output, ctx);
64
+ });
65
+ register('generate_barcode', 'Send a barcode payload to Imazeo and generate a static barcode. May spend credits. Saves PNG or SVG locally.', z.strictObject({ options: barcodeOptions, output, ...processing }), 'create', async ({ options, output, quoteId, idempotencyKey }, ctx) => {
66
+ await ctx.files.prepare(output, codeMime(options.format));
67
+ const result = await (await ctx.api.project()).barcodes.generate(options, ctx.signal, { quoteId, idempotencyKey });
68
+ return saveResult(result, output, ctx);
69
+ });
70
+ register('inspect_pdf', 'Upload a local PDF to Imazeo to get its page count and dimensions. May spend credits.', z.strictObject({ input: pathInput, ...processing }), 'create', async ({ input, quoteId, idempotencyKey }, { api, files, signal }) => {
71
+ const [file] = await files.readMany([input], pdf, signal);
72
+ return { info: await (await api.project()).pdf.info(file, { quoteId, idempotencyKey, signal }) };
73
+ });
74
+ register('render_pdf', 'Upload a local PDF to Imazeo to render up to 10 selected pages as images. May spend credits. Multiple pages use a -pN filename suffix.', z.strictObject({
75
+ input: pathInput, output, selection: pdfSelection.optional(),
76
+ format: rasterFormat.optional(), scale: z.number().min(0.5).max(2).optional(),
77
+ quality: z.int().min(1).max(100).optional(), ...processing,
78
+ }), 'create', async ({ input, output, selection, format, scale, quality, quoteId, idempotencyKey }, ctx) => {
79
+ const pages = renderPages(selection);
80
+ if (pages.length > 10)
81
+ throw new ToolError('INVALID_SELECTION', 'Select up to 10 pages per render.');
82
+ const mime = 'image/' + (format ?? 'png');
83
+ await ctx.files.prepare(output, mime, pages.length === 1 ? undefined : pages);
84
+ const [file] = await ctx.files.readMany([input], pdf, ctx.signal);
85
+ const result = await (await ctx.api.project()).pdf.render(file, {
86
+ ...pdfQuery(selection), format, scale, quality, quoteId, idempotencyKey, signal: ctx.signal,
87
+ });
88
+ return ctx.files.save(output, 'data' in result
89
+ ? [{ ...result, pageNumber: result.pdfPage }]
90
+ : pdfPages(result.pages), ctx.signal);
91
+ });
92
+ register('merge_pdfs', 'Upload two to ten local PDFs to Imazeo and merge them in the supplied order. May spend credits. Saves a PDF locally.', z.strictObject({ inputs: z.array(pathInput).min(2).max(10), output, ...processing }), 'create', async ({ inputs, output, quoteId, idempotencyKey }, ctx) => {
93
+ await ctx.files.prepare(output, 'application/pdf');
94
+ const files = await ctx.files.readMany(inputs, pdf, ctx.signal);
95
+ const result = await (await ctx.api.project()).pdf.merge(files, { quoteId, idempotencyKey, signal: ctx.signal });
96
+ return saveResult(result, output, ctx);
97
+ });
98
+ register('extract_pdf_pages', 'Upload a local PDF to Imazeo to extract specified pages. May spend credits. Saves a PDF locally.', z.strictObject({ input: pathInput, output, selection: pdfSelection, ...processing }), 'create', async ({ input, output, selection, quoteId, idempotencyKey }, ctx) => {
99
+ await ctx.files.prepare(output, 'application/pdf');
100
+ const [file] = await ctx.files.readMany([input], pdf, ctx.signal);
101
+ const result = await (await ctx.api.project()).pdf.extract(file, {
102
+ ...pdfQuery(selection), quoteId, idempotencyKey, signal: ctx.signal,
103
+ });
104
+ return saveResult(result, output, ctx);
105
+ });
106
+ register('download_output', 'Download a private original, retained transformation, saved artifact, or completed conversion from Imazeo to a new local file. Project bandwidth limits can apply.', z.strictObject({
107
+ source: z.enum(['original', 'transform', 'artifact', 'conversion']),
108
+ id, output,
109
+ }), 'download', async ({ source, id, output }, ctx) => {
110
+ await ctx.files.prepare(output);
111
+ const sdk = await ctx.api.project();
112
+ const downloads = {
113
+ original: async () => {
114
+ const result = await sdk.images.download(id, ctx.signal);
115
+ if (result.contentType === 'application/octet-stream' && result.format === 'svg') {
116
+ return { ...result, contentType: 'image/svg+xml' };
117
+ }
118
+ return result;
119
+ },
120
+ transform: () => sdk.transforms.download(id, { signal: ctx.signal }),
121
+ artifact: () => sdk.artifacts.download(id),
122
+ conversion: () => sdk.conversions.download(id),
123
+ };
124
+ return saveResult(await downloads[source](), output, ctx);
125
+ });
126
+ register('list_originals', 'List originals uploaded to the key’s project. Use an image ID in transform_image or download_output.', z.strictObject({
127
+ page: z.int().min(1).optional(), limit: z.int().min(1).max(100).optional(),
128
+ q: z.string().min(1).max(100).optional(),
129
+ }), 'read', async (query, { api, signal }) => (await api.project()).images.list(query, signal));
130
+ register('list_outputs', 'List private outputs and originals associated with the key’s project. Use each item’s downloadSource and ID to download it.', z.strictObject({
131
+ page: z.int().min(1).optional(), limit: z.int().min(1).max(100).optional(),
132
+ q: z.string().min(1).max(100).optional(),
133
+ type: z.enum(['all', 'original', 'transform', 'qr', 'barcode', 'pdf', 'docx', 'xlsx', 'pptx', 'website']).optional(),
134
+ scope: z.enum(['all', 'generated']).optional(),
135
+ }), 'read', async (query, { api }) => {
136
+ const { items, ...page } = await (await api.project()).outputs.list(query);
137
+ return {
138
+ ...page,
139
+ items: items.map(({ meta: _meta, ...item }) => ({
140
+ ...item,
141
+ downloadSource: item.kind === 'original' || item.kind === 'transform' ? item.kind : 'artifact',
142
+ })),
143
+ };
144
+ });
145
+ register('save_artifact', 'Upload a locally generated preview to Imazeo as a private project artifact. Uses project storage. Confirm the upload.', z.strictObject({
146
+ input: pathInput, name: z.string().trim().min(1).max(120),
147
+ kind: z.enum(['qr', 'barcode', 'pdf_render', 'pdf_merge', 'pdf_extract', 'image_transform']),
148
+ sourceImageId: id.optional(), confirm: confirmation,
149
+ }), 'create', async ({ input, name, kind, sourceImageId }, { api, files, signal }) => {
150
+ const [file] = await files.readMany([input], artifactTypes[kind], signal);
151
+ if (!file?.contentType) {
152
+ throw new ToolError('INVALID_FILE_TYPE', 'The preview must have a supported media extension.');
153
+ }
154
+ const artifact = await (await api.project()).artifacts.save(file, {
155
+ displayName: name, kind, contentType: file.contentType, sourceImageId,
156
+ });
157
+ const { requestSnapshot: _snapshot, ...metadata } = artifact;
158
+ return { artifact: metadata };
159
+ });
160
+ }
@@ -0,0 +1,112 @@
1
+ import { z } from 'zod';
2
+ import { documentTypes } from '../files.js';
3
+ import { ToolError } from '../errors.js';
4
+ import { saveResult } from './media.js';
5
+ import { confirmation, conversion, conversionEngines, httpUrl, id, idempotencyKey, output, pagination, processing, qrOptions, quoteKinds, } from '../schemas.js';
6
+ const dynamicStatus = z.enum(['active', 'paused', 'deleted']);
7
+ const name = z.string().trim().min(1).max(100);
8
+ function jobSummary(job) {
9
+ const { options: _options, result, ...metadata } = job;
10
+ if (!result)
11
+ return { ...metadata, result };
12
+ const { warnings: _warnings, ...dimensions } = result;
13
+ return { ...metadata, result: dimensions };
14
+ }
15
+ export function registerProject(register) {
16
+ register('project_capabilities', 'Check the Imazeo project ID and optionally read conversion, dynamic QR, or output availability information.', z.strictObject({ detail: z.enum(['identity', 'conversions', 'dynamic_qr', 'outputs']).optional() }), 'read', async ({ detail }, { api }) => {
17
+ if (!detail || detail === 'identity')
18
+ return api.context();
19
+ const sdk = await api.project();
20
+ if (detail === 'conversions')
21
+ return { conversions: await sdk.conversions.capabilities() };
22
+ if (detail === 'dynamic_qr')
23
+ return { dynamicQr: await sdk.dynamicCodes.capabilities() };
24
+ return { outputs: await sdk.outputs.summary() };
25
+ });
26
+ register('quote_credits', 'Request an expiring Imazeo processing quote without running the operation or spending processing credits. Set remote for a transform using a public source URL.', z.strictObject({
27
+ kind: z.enum(quoteKinds),
28
+ units: z.int().min(1).max(100).describe('Measurable units for the operation. Common cases use one unit.'),
29
+ remote: z.boolean().optional(),
30
+ }), 'create', async ({ kind, units, remote }, { api }) => {
31
+ if ((remote && kind !== 'image.transform') || (kind === 'pdf.render' ? units > 10 : units !== 1)) {
32
+ throw new ToolError('INVALID_INPUT', 'Quote one unit per operation or up to 10 for PDF rendering. Only URL image transforms use the remote flag.');
33
+ }
34
+ return { quote: await (await api.project()).credits.quote({ kind, units, remote }) };
35
+ });
36
+ register('get_operation', 'Read the status of an Imazeo processing operation by its operation ID or recover it using the original operation kind and idempotency key.', z.strictObject({
37
+ lookup: z.discriminatedUnion('by', [
38
+ z.strictObject({ by: z.literal('id'), id }),
39
+ z.strictObject({
40
+ by: z.literal('key'), kind: z.enum([...quoteKinds, 'remote.fetch']), idempotencyKey,
41
+ }),
42
+ ]),
43
+ }), 'read', async ({ lookup }, { api }) => {
44
+ const { operations } = await api.project();
45
+ const operation = lookup.by === 'id'
46
+ ? await operations.get(lookup.id)
47
+ : await operations.lookup({ kind: lookup.kind, key: lookup.idempotencyKey });
48
+ return { operation };
49
+ });
50
+ register('get_operation_result', 'Recover an available retained operation result from Imazeo. Returns PDF metadata or downloads media to a new local filename; multi-page PDF renders are numbered. Project bandwidth limits can apply.', z.strictObject({ id, output: output.optional() }), 'download', async ({ id, output }, ctx) => {
51
+ if (output)
52
+ await ctx.files.prepare(output);
53
+ const result = await (await ctx.api.project()).operations.result(id);
54
+ return saveResult(result, output, ctx);
55
+ });
56
+ register('submit_conversion', 'Queue a DOCX page, XLSX sheet or print page, PPTX slide, or public website capture. Sends the file or URL to Imazeo and reserves credits. Confirm after reviewing the matching one-unit quote.', z.strictObject({ source: conversion, ...processing }), 'idempotent', async ({ source, quoteId, idempotencyKey }, { api, files, signal }) => {
57
+ const request = { quoteId, idempotencyKey, signal };
58
+ if (source.engine === 'website') {
59
+ const job = await (await api.project()).conversions.website(source.url, request, source.options);
60
+ return { job: jobSummary(job) };
61
+ }
62
+ const extension = ('.' + source.engine);
63
+ const [file] = await files.readMany([source.input], { [extension]: documentTypes[extension] }, signal);
64
+ const { conversions } = await api.project();
65
+ const job = await conversions[source.engine](file, request, source.options);
66
+ return { job: jobSummary(job) };
67
+ });
68
+ register('get_conversion', 'Check an Imazeo conversion job by ID, or recover submission by the original idempotency key.', z.strictObject({
69
+ lookup: z.discriminatedUnion('by', [
70
+ z.strictObject({ by: z.literal('id'), id }),
71
+ z.strictObject({ by: z.literal('key'), idempotencyKey }),
72
+ ]),
73
+ }), 'read', async ({ lookup }, { api }) => {
74
+ const { conversions } = await api.project();
75
+ const job = lookup.by === 'id'
76
+ ? await conversions.get(lookup.id) : await conversions.lookup(lookup.idempotencyKey);
77
+ return { job: jobSummary(job) };
78
+ });
79
+ register('list_conversions', 'List recent Imazeo conversion jobs for one engine. Results may include temporary jobs.', z.strictObject({ engine: conversionEngines }), 'read', async ({ engine }, { api }) => {
80
+ const jobs = await (await api.project()).conversions.list(engine);
81
+ return { jobs: jobs.map(jobSummary) };
82
+ });
83
+ register('cancel_conversion', 'Request cancellation of an Imazeo conversion. The returned job is authoritative. Confirm before stopping work.', z.strictObject({ id, confirm: confirmation }), 'destructive', async ({ id }, { api }) => ({ job: jobSummary(await (await api.project()).conversions.cancel(id)) }));
84
+ register('save_conversion', 'Save a completed temporary conversion as a private Imazeo project artifact. Uses project storage. Confirm before saving.', z.strictObject({ id, confirm: confirmation }), 'idempotent', async ({ id }, { api }) => {
85
+ const { requestSnapshot: _snapshot, ...artifact } = await (await api.project()).conversions.save(id);
86
+ return { artifact };
87
+ });
88
+ register('list_dynamic_qr', 'List dynamic QR links in the Imazeo project, including revision and redirect URL.', z.strictObject({ ...pagination, status: dynamicStatus.optional(), search: z.string().max(100).optional() }), 'read', async (query, { api }) => (await api.project()).dynamicCodes.list(query));
89
+ register('get_dynamic_qr', 'Read one dynamic QR link and its current revision. Encode the redirect URL with generate_qr to make a local QR image.', z.strictObject({ id }), 'read', async ({ id }, { api }) => ({ code: await (await api.project()).dynamicCodes.get(id) }));
90
+ register('create_dynamic_qr', 'Create a managed Imazeo redirect for a dynamic QR code. Sends its name and destination to Imazeo and uses the project’s dynamic code quota. Confirm before creation.', z.strictObject({
91
+ name, destination: httpUrl, analyticsEnabled: z.boolean().optional(), idempotencyKey, confirm: confirmation,
92
+ }), 'idempotent', async ({ idempotencyKey, confirm: _confirm, ...input }, { api }) => ({ code: await (await api.project()).dynamicCodes.create(input, idempotencyKey) }));
93
+ register('update_dynamic_qr', 'Change a dynamic QR link’s destination, name, analytics, appearance options, or status. Setting deleted retires the link. Confirm against the current revision.', z.strictObject({
94
+ id, expectedRevision: z.int().min(0), name: name.optional(), destination: httpUrl.optional(),
95
+ status: dynamicStatus.optional(), analyticsEnabled: z.boolean().optional(),
96
+ qrOptions: qrOptions.optional(), idempotencyKey, confirm: confirmation,
97
+ }), 'destructive', async ({ id, idempotencyKey, confirm: _confirm, ...input }, { api }) => {
98
+ if (Object.values(input).filter((value) => value !== undefined).length < 2) {
99
+ throw new ToolError('INVALID_INPUT', 'Specify at least one dynamic QR field to change.');
100
+ }
101
+ return { code: await (await api.project()).dynamicCodes.update(id, input, idempotencyKey) };
102
+ });
103
+ register('get_dynamic_qr_analytics', 'Read aggregate scan counts for one Imazeo dynamic QR link. Supports plan-gated date ranges and filters.', z.strictObject({
104
+ id, days: z.int().min(1).max(90).optional(),
105
+ device: z.enum(['desktop', 'mobile', 'tablet', 'bot', 'unknown']).optional(),
106
+ browser: z.enum(['chrome', 'edge', 'firefox', 'safari', 'other', 'unknown']).optional(),
107
+ country: z.string().regex(/^(?:[A-Za-z]{2}|unknown)$/).optional(), bot: z.boolean().optional(),
108
+ }), 'read', async ({ id, ...query }, { api }) => {
109
+ const { recent: _recent, ...analytics } = await (await api.project()).dynamicCodes.analytics(id, query);
110
+ return { analytics };
111
+ });
112
+ }
@@ -0,0 +1,15 @@
1
+ # Architecture and API contract
2
+
3
+ The executable starts the official MCP TypeScript SDK's stdio server. Its factory accepts both 2025-era MCP initialization and 2026-07-28 discovery. Tool inputs use explicit JSON schemas and a matching runtime validator. Results provide structured content and a text representation for clients that display text only. Tools cover project workflows and retrieve permission-checked data on demand.
4
+
5
+ An adapter around the official `@imazeo/sdk` resolves the current project through `GET /v1/api-key/context`. The adapter pins the production origin, rejects redirects, bounds response reads, honors cancellation and captures request IDs, operation IDs and rate limit advice. Each MCP call can make a project-context request if the project ID has yet to be resolved, followed by the requested API action. A failed resolution can be attempted again on the next user call.
6
+
7
+ ## Production baseline
8
+
9
+ The contract follows Imazeo API 1.0.0 and the [published developer OpenAPI](https://imazeo.com/openapi/imazeo-developer.json). DOCX creation uses `POST /v1/projects/{projectId}/conversions`. XLSX, PPTX and website creation use their explicit engine suffixes on the same base route. The server reports remote job state and uses caller-directed status checks. Feature availability depends on project entitlements.
10
+
11
+ Processing uses an expiring credit quote, an explicit confirmation field and a user-retained UUID v4 idempotency key. The Imazeo API enforces quote ownership, expiry, pricing, request matching and plan admission. The server performs single attempts. Unknown or locally failed outcomes include recovery information with sanitized errors. When durable processing is disabled, use project usage to investigate uncertain outcomes before authorizing another attempt. Conversion jobs use their documented lookup route.
12
+
13
+ Local file access is opt-in and independent for reads and writes. Reads are confined to regular unlinked files below a configured root, with a combined byte limit. Each output is staged in its destination directory and linked into place exclusively, so a concurrent call cannot overwrite an existing file. Multi-page output returns any files already published if a later write fails. Use account-controlled directories to protect the local filesystem from concurrent changes by untrusted processes.
14
+
15
+ Account usage is available through the customer portal. MCP tools offer per-operation credit quotes, output counts, conversion and dynamic QR capabilities, and aggregate analytics. See [Security](../SECURITY.md) for the data transfer and credential boundaries.