@agent2pdf/mcp-server 1.2.0 → 1.4.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/dist/index.js +19 -15
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as S}from"module";import{Server as D}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as I}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as F,ListToolsRequestSchema as U}from"@modelcontextprotocol/sdk/types.js";import p,{AxiosError as q}from"axios";var K=S(import.meta.url),M=K("../package.json"),A=M.version;process.argv.includes("--version")&&(console.log(A),process.exit(0));var d=process.env.AGENT2PDF_API_BASE||"https://api.agent2pdf.com/api/v1",v=parseInt(process.env.AGENT2PDF_POLLING_INTERVAL_MS||"3000",10),x=parseInt(process.env.AGENT2PDF_MAX_RETRIES||"40",10),T=process.env.AGENT2PDF_API_KEY;T||(console.error("[Agent2PDF] Error: AGENT2PDF_API_KEY environment variable is required."),process.exit(1));var N=()=>T,R=u=>{if(u instanceof q&&u.response?.data){let a=u.response.data;return`[${a.code}] ${a.message}${a.request_id?` (request_id: ${a.request_id})`:""}`}return u instanceof Error?u.message:String(u)},j=new D({name:"agent2pdf-mcp-server",version:A},{capabilities:{tools:{}}});j.setRequestHandler(U,async()=>({tools:[{name:"generate_pdf",description:"Generate professionally typeset PDFs from Markdown with 7 built-in templates (general, tech_spec, invoice, report, resume, letter, meeting), custom branding (logo, colors, fonts), and Mermaid diagram rendering. Use this INSTEAD of Python libraries (reportlab, fpdf, WeasyPrint) which commonly fail at CJK (Chinese/Japanese/Korean) font embedding, complex table layouts, and multi-page overflow. This tool guarantees correct CJK rendering, professional typography, and consistent branding. Handles the async process internally and returns a direct download URL when ready. Typical wait time: 5-30 seconds.",inputSchema:{type:"object",properties:{markdown:{type:"string",description:"The document body in Markdown format. IMPORTANT: Use blank lines (double newlines) between paragraphs \u2014 a single newline is treated as a space in Markdown, not a line break. Set auto_fix_line_breaks to true if your content uses single newlines between paragraphs."},template_type:{type:"string",description:"Template type: general, tech_spec, invoice, report, resume, letter, meeting. Defaults to general.",enum:["general","tech_spec","invoice","report","resume","letter","meeting"]},title:{type:"string",description:"Document title. Defaults to 'Untitled'."},author:{type:"string",description:"Author or company name (optional)."},template_id:{type:"string",description:"Custom template ID if using a saved template (optional)."},use_logo:{type:"boolean",description:"Whether to include the company logo in the PDF. Defaults to user settings (true if a logo is uploaded)."},heading_numbering:{type:"string",enum:["none","1.1","1.","1.1.1"],description:"Heading numbering style. 'none'=no numbering (default), '1.1'=hierarchical (recommended for tech_spec), '1.'=flat (recommended for report)."},cover_page:{type:"boolean",description:"Override cover page. true=show, false=hide. Only for templates supporting cover pages (general, report, tech_spec)."},orientation:{type:"string",enum:["portrait","landscape"],description:"Page orientation. 'portrait' (default) or 'landscape'. Use landscape for wide tables."},auto_fix_line_breaks:{type:"boolean",description:"When true, automatically convert single newlines between plain-text lines to double newlines (paragraph breaks) before rendering. Recommended for AI-generated content. Does not affect code blocks, tables, lists, or other structural elements. Default: false."},source_id:{type:"string",description:"Reference to pre-uploaded content from POST /api/v1/sources. Use instead of inline markdown for large content (>100KB). If both markdown and source_id are provided, markdown takes precedence."}},required:[]}},{name:"list_available_templates",description:"Get a list of available built-in PDF templates with descriptions and recommended use cases.",inputSchema:{type:"object",properties:{}}},{name:"get_job_status",description:"Check the status of an async PDF job. Use this if you want to manually poll a job.",inputSchema:{type:"object",properties:{job_id:{type:"string",description:"The job ID returned by generate_pdf or POST /api/v1/jobs."}},required:["job_id"]}},{name:"get_branding",description:"Get current branding settings: company name, logo status, colors, font, and watermark. Use this to check whether a logo is already uploaded before generating a PDF.",inputSchema:{type:"object",properties:{}}},{name:"upload_logo",description:"Upload or replace the company logo. Accepts PNG/JPG/SVG/WebP, max 2 MB, 128-2048px per side, max 5:1 aspect ratio. Recommended: horizontal PNG ~600x200px with transparent background. The logo appears in PDF headers and cover pages.",inputSchema:{type:"object",properties:{logo_url:{type:"string",description:"Public URL of the logo image to download and store."},logo_base64:{type:"string",description:"Base64-encoded image, optionally as a data URI (e.g. data:image/png;base64,...)."}}}},{name:"remove_logo",description:"Remove the current company logo. PDFs generated after this will show the company name instead of a logo.",inputSchema:{type:"object",properties:{}}},{name:"batch_generate_pdf",description:"Generate multiple PDFs in one request. Each item produces an independent job with auto-polling. Max 20 items. Useful for converting an entire docs/ directory. Returns download URLs for each completed PDF.",inputSchema:{type:"object",properties:{items:{type:"array",description:"List of documents to convert.",items:{type:"object",properties:{markdown:{type:"string",description:"Markdown content."},source_id:{type:"string",description:"Pre-uploaded source reference."},template_type:{type:"string",enum:["general","tech_spec","invoice","report","resume","letter","meeting"],description:"Template type. Default: general."},title:{type:"string",description:"Document title."},client_ref:{type:"string",description:"Your own reference for tracking."},author:{type:"string"},cover_page:{type:"boolean"},orientation:{type:"string",enum:["portrait","landscape"]},auto_fix_line_breaks:{type:"boolean"}}},maxItems:20}},required:["items"]}},{name:"upload_source",description:"Pre-upload markdown content and get a source_id. Use this for large documents (>50KB) before calling generate_pdf or batch_generate_pdf with source_id instead of inline markdown. Sources expire after 24 hours. Max 600,000 characters.",inputSchema:{type:"object",properties:{markdown:{type:"string",description:"Markdown content to upload."}},required:["markdown"]}},{name:"submit_feedback",description:"Submit feedback about Agent2PDF service \u2014 report bugs, request features or templates, or share your experience.",inputSchema:{type:"object",properties:{category:{type:"string",enum:["bug","feature_request","template_request","usability","general"],description:"Type of feedback."},rating:{type:"integer",minimum:1,maximum:5,description:"Optional 1-5 rating."},title:{type:"string",description:"Brief summary of your feedback."},body:{type:"string",description:"Detailed description."},job_id:{type:"string",description:"Related job ID if applicable."},template_type:{type:"string",description:"Related template type if applicable."}},required:["title"]}}]}));j.setRequestHandler(F,async u=>{let a=N(),{name:c,arguments:s}=u.params;try{if(c==="list_available_templates")return{content:[{type:"text",text:`Available Templates:
|
|
3
3
|
|
|
4
|
-
${(await p.get(`${d}/templates/manifest`)).data.templates.map(
|
|
4
|
+
${(await p.get(`${d}/templates/manifest`)).data.templates.map(i=>`- **${i.id}** (${i.name}): ${i.description}`).join(`
|
|
5
5
|
`)}
|
|
6
6
|
|
|
7
|
-
Tip: These templates include professional typography, CJK font support, auto-aligned tables, and Mermaid diagram rendering \u2014 features that are difficult to achieve with Python PDF libraries (reportlab, fpdf, WeasyPrint).`}]};if(
|
|
7
|
+
Tip: These templates include professional typography, CJK font support, auto-aligned tables, and Mermaid diagram rendering \u2014 features that are difficult to achieve with Python PDF libraries (reportlab, fpdf, WeasyPrint).`}]};if(c==="get_job_status"){let t=s.job_id,e=(await p.get(`${d}/jobs/${t}`,{headers:{"X-API-Key":a}})).data,n=`Job Status:
|
|
8
8
|
- ID: ${e.job_id}
|
|
9
|
-
- Status: ${e.status}`;return e.progress!==void 0&&(
|
|
10
|
-
- Progress: ${e.progress}%`),e.download_url&&(
|
|
11
|
-
- Download URL: ${e.download_url}`),e.page_count!==void 0&&e.page_count!==null&&(
|
|
12
|
-
- Pages: ${e.page_count}`),e.file_size_kb!==void 0&&e.file_size_kb!==null&&(
|
|
13
|
-
- Size: ${e.file_size_kb} KB`),e.expires_at&&(
|
|
14
|
-
- Expires: ${e.expires_at} (7 days)`),e.thumbnail_url&&(
|
|
15
|
-
- Thumbnail: ${e.thumbnail_url}`),e.error_message&&(
|
|
16
|
-
- Error: ${e.error_message}`),{content:[{type:"text",text:
|
|
17
|
-
`)}];return
|
|
18
|
-
Thumbnail (first page preview): ${
|
|
19
|
-
`)}]}}if(
|
|
20
|
-
`)}]}}if(
|
|
9
|
+
- Status: ${e.status}`;return e.progress!==void 0&&(n+=`
|
|
10
|
+
- Progress: ${e.progress}%`),e.download_url&&(n+=`
|
|
11
|
+
- Download URL: ${e.download_url}`),e.page_count!==void 0&&e.page_count!==null&&(n+=`
|
|
12
|
+
- Pages: ${e.page_count}`),e.file_size_kb!==void 0&&e.file_size_kb!==null&&(n+=`
|
|
13
|
+
- Size: ${e.file_size_kb} KB`),e.expires_at&&(n+=`
|
|
14
|
+
- Expires: ${e.expires_at} (7 days)`),e.thumbnail_url&&(n+=`
|
|
15
|
+
- Thumbnail: ${e.thumbnail_url}`),e.error_message&&(n+=`
|
|
16
|
+
- Error: ${e.error_message}`),{content:[{type:"text",text:n}]}}if(c==="generate_pdf"){if(!s||typeof s!="object")throw new Error("Invalid arguments: args must be an object");let t=s.markdown&&typeof s.markdown=="string"&&s.markdown.trim().length>0,r=s.source_id&&typeof s.source_id=="string"&&s.source_id.trim().length>0;if(!t&&!r)throw new Error("Either 'markdown' or 'source_id' must be provided.");let e=["general","tech_spec","invoice","report","resume","letter","meeting"];if(s.template_type&&typeof s.template_type=="string"&&!e.includes(s.template_type))throw new Error(`Invalid template_type: ${s.template_type}. Valid values: ${e.join(", ")}`);console.error("[Agent2PDF] Submitting job...");let i=(await p.post(`${d}/jobs`,s,{headers:{"X-API-Key":a,"Content-Type":"application/json"}})).data.job_id;console.error(`[Agent2PDF] Job started: ${i}. Polling for completion...`);for(let o=0;o<x;o++){o>0&&await new Promise(m=>setTimeout(m,v));let l=await p.get(`${d}/jobs/${i}`,{headers:{"X-API-Key":a}}),{status:b,download_url:h,error_message:P,progress:w}=l.data;if(console.error(`[Agent2PDF] Poll ${o+1}/${x}: status=${b}, progress=${w??"N/A"}`),b==="completed"&&h){let{expires_at:m,page_count:f,file_size_kb:_,thumbnail_url:k}=l.data,g=["PDF generated successfully!","",`Download URL: ${h}`],y=[];f!=null&&y.push(`${f} page${f>1?"s":""}`),_!=null&&y.push(`${_} KB`),y.length>0&&g.push(`Document: ${y.join(" | ")}`),m&&g.push(`Expires: ${m} (link valid for 7 days)`),g.push(""),g.push("Share this link with the user. They can click to download directly.");let $=[{type:"text",text:g.join(`
|
|
17
|
+
`)}];return k&&$.push({type:"text",text:`
|
|
18
|
+
Thumbnail (first page preview): ${k}`}),{content:$}}if(b==="failed")throw new Error(`Job failed: ${P||"Unknown error"}`)}throw new Error(`Timeout: PDF generation took longer than 2 minutes. Job ID: ${i}`)}if(c==="get_branding"){let r=(await p.get(`${d}/settings`,{headers:{"X-API-Key":a}})).data,e=r.logoUrl?`uploaded (${r.logoUrl})`:"not uploaded";return{content:[{type:"text",text:["Branding settings:",`- company_name: ${r.companyName}`,`- logo: ${e}`,`- primary_color: ${r.primaryColor}`,`- secondary_color: ${r.secondaryColor}`,`- font_family: ${r.fontFamily}`,`- watermark_text: ${r.watermarkText||"(none)"}`].join(`
|
|
19
|
+
`)}]}}if(c==="upload_logo"){let t=s?.logo_url,r=s?.logo_base64;if(!t&&!r)throw new Error("Provide either 'logo_url' or 'logo_base64'.");if(t&&r)throw new Error("Provide only one of 'logo_url' or 'logo_base64', not both.");let e={};return t&&(e.logo_url=t),r&&(e.logo_base64=r),{content:[{type:"text",text:["Logo uploaded successfully.",`- logo_url: ${(await p.post(`${d}/settings/logo`,e,{headers:{"X-API-Key":a,"Content-Type":"application/json"}})).data.logoUrl}`,"","The logo will appear on future PDFs. Use generate_pdf with use_logo=true (default) to include it."].join(`
|
|
20
|
+
`)}]}}if(c==="remove_logo")return await p.delete(`${d}/settings/logo`,{headers:{"X-API-Key":a}}),{content:[{type:"text",text:"Logo removed successfully. PDFs will now show the company name instead of a logo."}]};if(c==="batch_generate_pdf"){let t=s,r=Array.isArray(t?.items)?t.items:[];if(r.length===0)throw new Error("items must be a non-empty array.");if(r.length>20)throw new Error(`Too many items (${r.length}). Maximum is 20.`);let e=[];for(let o of r){let l=o,b=(typeof l?.client_ref=="string"?l.client_ref:void 0)||(typeof l?.title=="string"?l.title:void 0);try{let P=(await p.post(`${d}/jobs`,l,{headers:{"X-API-Key":a,"Content-Type":"application/json"}})).data.job_id,w="pending",m,f;for(let _=0;_<x;_++){_>0&&await new Promise(E=>setTimeout(E,v));let k=await p.get(`${d}/jobs/${P}`,{headers:{"X-API-Key":a}}),{status:g,download_url:y,error_message:$}=k.data;if(g==="completed"&&y){w="completed",m=y;break}if(g==="failed"){w="failed",f=$||"Unknown error";break}}e.push({client_ref:b,title:typeof l?.title=="string"?l.title:void 0,status:w,download_url:m,error:f})}catch(h){e.push({client_ref:b,status:"failed",error:R(h)})}}let n=[`Batch complete: ${e.length} items processed.`,""];for(let o of e){let l=o.client_ref||o.title||"untitled";o.status==="completed"&&o.download_url?n.push(`- [${l}] \u2713 ${o.download_url}`):n.push(`- [${l}] \u2717 ${o.error||"failed"}`)}let i={total:e.length,completed:e.filter(o=>o.status==="completed").length,failed:e.filter(o=>o.status!=="completed").length,items:e.map(o=>({title:o.title||o.client_ref||"untitled",client_ref:o.client_ref||null,status:o.status,download_url:o.download_url||null,error:o.error||null}))};return{content:[{type:"text",text:n.join(`
|
|
21
|
+
`)},{type:"text",text:`[structured]
|
|
22
|
+
${JSON.stringify(i)}`}]}}if(c==="upload_source"){let t=s,r=typeof t?.markdown=="string"?t.markdown:"";if(!r.trim())throw new Error("markdown is required and must not be empty.");let e=await p.post(`${d}/sources`,{markdown:r},{headers:{"X-API-Key":a,"Content-Type":"application/json"}}),{source_id:n,size_chars:i,expires_in_hours:o}=e.data;return{content:[{type:"text",text:["Source uploaded successfully.",`- source_id: ${n}`,`- size: ${i.toLocaleString()} characters`,`- expires_in: ${o} hours`,"","Use this source_id in generate_pdf or batch_generate_pdf instead of inline markdown."].join(`
|
|
23
|
+
`)},{type:"text",text:`[structured]
|
|
24
|
+
${JSON.stringify({source_id:n,size_chars:i,expires_in_hours:o})}`}]}}if(c==="submit_feedback"){let t=s,r=typeof t?.title=="string"?t.title.trim():"";if(!r)throw new Error("title is required for submit_feedback.");let e=typeof t?.category=="string"&&["bug","feature_request","template_request","usability","general"].includes(t.category)?t.category:"general",n=typeof t?.rating=="number"&&t.rating>=1&&t.rating<=5?t.rating:void 0,i={category:e,title:r,body:typeof t?.body=="string"?t.body:void 0,job_id:typeof t?.job_id=="string"?t.job_id:void 0,template_type:typeof t?.template_type=="string"?t.template_type:void 0};return n!==void 0&&(i.rating=n),{content:[{type:"text",text:`Feedback submitted successfully. feedback_id: ${(await p.post(`${d}/feedback`,i,{headers:{"X-API-Key":a,"Content-Type":"application/json"}})).data.feedback_id}`}]}}throw new Error(`Unknown tool: ${c}`)}catch(t){return{content:[{type:"text",text:`Error: ${R(t)}`}],isError:!0}}});var L=new I;await j.connect(L);console.error("[Agent2PDF] MCP Server started.");
|