aem-mcp-server 1.1.4 → 1.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEM MCP Server (aem-mcp-server)
2
2
 
3
- [![Version](https://img.shields.io/npm/v/@easingthemes/aem-mcp-server.svg)](https://npmjs.org/package/aem-mcp-server)
3
+ [![Version](https://img.shields.io/npm/v/aem-mcp-server.svg)](https://npmjs.org/package/aem-mcp-server)
4
4
  [![Release Status](https://github.com/easingthemes/aem-mcp-server/actions/workflows/release.yml/badge.svg)](https://github.com/easingthemes/aem-mcp-server/actions/workflows/release.yml)
5
5
  [![CodeQL Analysis](https://github.com/easingthemes/aem-mcp-server/workflows/CodeQL/badge.svg?branch=main)](https://github.com/easingthemes/aem-mcp-server/actions)
6
6
  [![semver: semantic-release](https://img.shields.io/badge/semver-semantic--release-blue.svg)](https://github.com/semantic-release/semantic-release)
@@ -106,3 +106,8 @@ List all components on MyPage
106
106
  ## API Documentation
107
107
 
108
108
  For detailed API documentation, please refer to the [API Docs](docs/API.md).
109
+
110
+ ## Similar Projects
111
+
112
+ - https://github.com/indrasishbanerjee/aem-mcp-server (Used as a base for this project)
113
+ - https://www.npmjs.com/package/@myea/aem-mcp-handler (Looks like an original source of the above project)
@@ -0,0 +1 @@
1
+ "use strict";const i="https://ims-na1.adobelogin.com/ims/token",s="openid,AdobeID,read_organizations,additional_info.projectedProductContext,aem_author_read,aem_author_write",c=t=>t?Array.isArray(t)?t.join(","):t:s;export async function getAccessToken(t,r,n){if(!t||!r)throw new Error("Client ID and Client Secret must be provided");const o=c(n),a=new URLSearchParams({client_id:t,client_secret:r,grant_type:"client_credentials",scope:o}),e=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()});if(!e.ok)throw new Error(`IMS token request failed: ${e.status} ${await e.text()}`);return(await e.json()).access_token}
@@ -1 +1 @@
1
- "use strict";export function getAEMConfig(t){return{contentPaths:{sitesRoot:"/content",assetsRoot:"/content/dam",templatesRoot:"/conf",experienceFragmentsRoot:"/content/experience-fragments"},replication:{publisherUrls:t.AEM_PUBLISHER_URLS?.split(",")||["http://localhost:4503"],defaultReplicationAgent:"publish"},components:{defaultProperties:{"jcr:primaryType":"nt:unstructured","sling:resourceType":"foundation/components/text"}},queries:{maxLimit:parseInt(t.AEM_QUERY_MAX_LIMIT||"100"),defaultLimit:parseInt(t.AEM_QUERY_DEFAULT_LIMIT||"20"),timeoutMs:parseInt(t.AEM_QUERY_TIMEOUT||"30000")},validation:{maxDepth:parseInt(t.AEM_MAX_DEPTH||"5"),allowedLocales:["en"]}}}export function isValidContentPath(t,n){return Object.values(n.contentPaths).some(e=>t.startsWith(e))}export function isValidLocale(t,n){if(!t)return!1;const o=t.toLowerCase();return n.validation.allowedLocales.some(e=>e.toLowerCase()===o||o==="en"&&e.toLowerCase().startsWith("en"))}
1
+ "use strict";export function getAEMConfig(t){return{contentPaths:{sitesRoot:"/content",assetsRoot:"/content/dam",templatesRoot:"/conf",experienceFragmentsRoot:"/content/experience-fragments"},replication:{publisherUrls:t.AEM_PUBLISHER_URLS?.split(",")||["http://localhost:4503"],defaultReplicationAgent:"publish"},components:{defaultProperties:{"jcr:primaryType":"nt:unstructured","sling:resourceType":"foundation/components/text"}},queries:{maxLimit:parseInt(t.AEM_QUERY_MAX_LIMIT||"100"),defaultLimit:parseInt(t.AEM_QUERY_DEFAULT_LIMIT||"20"),timeoutMs:parseInt(t.AEM_QUERY_TIMEOUT||"30000")},validation:{maxDepth:parseInt(t.AEM_MAX_DEPTH||"5"),allowedLocales:t.AEM_ALLOWED_LOCALES?.split(",")||["en"]}}}export function isValidContentPath(t,n){return Object.values(n.contentPaths).some(e=>t.startsWith(e))}export function isValidLocale(t,n){if(!t)return!1;const o=t.toLowerCase();return n.validation.allowedLocales.some(e=>e.toLowerCase()===o||o==="en"&&e.toLowerCase().startsWith("en"))}
@@ -1 +1 @@
1
- "use strict";import P from"axios";import{getAEMConfig as b,isValidContentPath as u,isValidLocale as w}from"./aem.config.js";import{createAEMError as d,handleAEMHttpError as y,safeExecute as l,validateComponentOperation as A,createSuccessResponse as p,AEM_ERROR_CODES as m}from"./aem.errors.js";export class AEMConnector{config;auth;aemConfig;constructor(n){this.config=this.loadConfig(n),this.aemConfig=b({}),this.auth={username:this.config.aem.serviceUser.username,password:this.config.aem.serviceUser.password}}loadConfig(n={}){return{aem:{host:n.host||"http://localhost:4502",author:n.host||"http://localhost:4502",publish:"http://localhost:4503",serviceUser:{username:n.user||"admin",password:n.pass||"admin"},endpoints:{content:"/content",dam:"/content/dam",query:"/bin/querybuilder.json",crxde:"/crx/de",jcr:""}},mcp:{name:"AEM MCP Server",version:"1.0.0"}}}createAxiosInstance(){return P.create({baseURL:this.config.aem.host,auth:this.auth,timeout:3e4,headers:{"Content-Type":"application/json",Accept:"application/json"}})}async testConnection(){try{console.log("Testing AEM connection to:",this.config.aem.host);const t=await this.createAxiosInstance().get("/libs/granite/core/content/login.html",{timeout:5e3,validateStatus:s=>s<500});return console.log("\u2705 AEM connection successful! Status:",t.status),!0}catch(n){return console.error("\u274C AEM connection failed:",n.message),n.response&&(console.error(" Status:",n.response.status),console.error(" URL:",n.config?.url)),!1}}async validateComponent(n){return l(async()=>{const t=n.locale,s=n.pagePath||n.page_path,r=n.component,a=n.props;if(A(t,s,r,a),!w(t,this.aemConfig))throw d(m.INVALID_LOCALE,`Locale '${t}' is not supported`,{locale:t,allowedLocales:this.aemConfig.validation.allowedLocales});if(!u(s,this.aemConfig))throw d(m.INVALID_PATH,`Path '${s}' is not within allowed content roots`,{path:s,allowedRoots:Object.values(this.aemConfig.contentPaths)});const o=await this.createAxiosInstance().get(`${s}.json`,{params:{":depth":"2"},timeout:this.aemConfig.queries.timeoutMs}),c=this.validateComponentProps(o.data,r,a);return p({message:"Component validation completed successfully",pageData:o.data,component:r,locale:t,validation:c,configUsed:{allowedLocales:this.aemConfig.validation.allowedLocales}},"validateComponent")},"validateComponent")}validateComponentProps(n,t,s){const r=[],a=[];return t==="text"&&!s.text&&!s.richText&&r.push("Text component should have text or richText property"),t==="image"&&!s.fileReference&&!s.src&&a.push("Image component requires fileReference or src property"),{valid:a.length===0,errors:a,warnings:r,componentType:t,propsValidated:Object.keys(s).length}}async updateComponent(n){return l(async()=>{if(!n.componentPath||typeof n.componentPath!="string")throw d(m.INVALID_PARAMETERS,"Component path is required and must be a string");if(!n.properties||typeof n.properties!="object")throw d(m.INVALID_PARAMETERS,"Properties are required and must be an object");if(!u(n.componentPath,this.aemConfig))throw d(m.INVALID_PATH,`Component path '${n.componentPath}' is not within allowed content roots`,{path:n.componentPath,allowedRoots:Object.values(this.aemConfig.contentPaths)});const t=this.createAxiosInstance();try{await t.get(`${n.componentPath}.json`)}catch(e){throw e.response?.status===404?d(m.COMPONENT_NOT_FOUND,`Component not found at path: ${n.componentPath}`,{componentPath:n.componentPath}):y(e,"updateComponent")}const s=new URLSearchParams;Object.entries(n.properties).forEach(([e,o])=>{o==null?s.append(`${e}@Delete`,""):Array.isArray(o)?o.forEach(c=>{s.append(`${e}`,c.toString())}):typeof o=="object"?s.append(e,JSON.stringify(o)):s.append(e,o.toString())});const r=await t.post(n.componentPath,s,{headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},timeout:this.aemConfig.queries.timeoutMs}),a=await t.get(`${n.componentPath}.json`);return p({message:"Component updated successfully",path:n.componentPath,properties:n.properties,updatedProperties:a.data,response:r.data,verification:{success:!0,propertiesChanged:Object.keys(n.properties).length,timestamp:new Date().toISOString()}},"updateComponent")},"updateComponent")}async undoChanges(n){return p({message:"undoChanges is not implemented. Please use AEM version history for undo/rollback.",request:n,timestamp:new Date().toISOString()},"undoChanges")}async scanPageComponents(n){return l(async()=>{const s=await this.createAxiosInstance().get(`${n}.infinity.json`),r=[],a=(e,o)=>{!e||typeof e!="object"||(e["sling:resourceType"]&&r.push({path:o,resourceType:e["sling:resourceType"],properties:{...e}}),Object.entries(e).forEach(([c,i])=>{if(typeof i=="object"&&i!==null&&!c.startsWith("rep:")&&!c.startsWith("oak:")){const h=o?`${o}/${c}`:c;a(i,h)}}))};return s.data["jcr:content"]?a(s.data["jcr:content"],"jcr:content"):a(s.data,n),p({pagePath:n,components:r,totalComponents:r.length},"scanPageComponents")},"scanPageComponents")}async fetchSites(){return l(async()=>{const t=await this.createAxiosInstance().get("/content.json",{params:{":depth":"2"}}),s=[];return Object.entries(t.data).forEach(([r,a])=>{r.startsWith("jcr:")||r.startsWith("sling:")||a&&typeof a=="object"&&a["jcr:content"]&&s.push({name:r,path:`/content/${r}`,title:a["jcr:content"]["jcr:title"]||r,template:a["jcr:content"]["cq:template"],lastModified:a["jcr:content"]["cq:lastModified"]})}),p({sites:s,totalCount:s.length},"fetchSites")},"fetchSites")}async fetchLanguageMasters(n){return l(async()=>{const s=await this.createAxiosInstance().get(`/content/${n}.json`,{params:{":depth":"3"}}),r=[];return Object.entries(s.data).forEach(([a,e])=>{a.startsWith("jcr:")||a.startsWith("sling:")||e&&typeof e=="object"&&e["jcr:content"]&&r.push({name:a,path:`/content/${a}`,title:e["jcr:content"]["jcr:title"]||a,language:e["jcr:content"]["jcr:language"]||"en"})}),p({site:n,languageMasters:r},"fetchLanguageMasters")},"fetchLanguageMasters")}async fetchAvailableLocales(n,t){return l(async()=>{const r=await this.createAxiosInstance().get(`${t}.json`,{params:{":depth":"2"}}),a=[];return Object.entries(r.data).forEach(([e,o])=>{e.startsWith("jcr:")||e.startsWith("sling:")||o&&typeof o=="object"&&a.push({name:e,title:o["jcr:content"]?.["jcr:title"]||e,language:o["jcr:content"]?.["jcr:language"]||e})}),p({site:n,languageMasterPath:t,availableLocales:a},"fetchAvailableLocales")},"fetchAvailableLocales")}async replicateAndPublish(n,t,s){return l(async()=>p({message:"Replication simulated",selectedLocales:n,componentData:t,localizedOverrides:s},"replicateAndPublish"),"replicateAndPublish")}async getAllTextContent(n){return l(async()=>{const s=await this.createAxiosInstance().get(`${n}.infinity.json`),r=[],a=(e,o)=>{!e||typeof e!="object"||((e.text||e["jcr:title"]||e["jcr:description"])&&r.push({path:o,title:e["jcr:title"],text:e.text,description:e["jcr:description"]}),Object.entries(e).forEach(([c,i])=>{if(typeof i=="object"&&i!==null&&!c.startsWith("rep:")&&!c.startsWith("oak:")){const h=o?`${o}/${c}`:c;a(i,h)}}))};return s.data["jcr:content"]?a(s.data["jcr:content"],"jcr:content"):a(s.data,n),p({pagePath:n,textContent:r},"getAllTextContent")},"getAllTextContent")}async getPageTextContent(n){return l(async()=>this.getAllTextContent(n),"getPageTextContent")}async getPageImages(n){return l(async()=>{const s=await this.createAxiosInstance().get(`${n}.infinity.json`),r=[],a=(e,o)=>{!e||typeof e!="object"||((e.fileReference||e.src)&&r.push({path:o,fileReference:e.fileReference,src:e.src,alt:e.alt||e.altText,title:e["jcr:title"]||e.title}),Object.entries(e).forEach(([c,i])=>{if(typeof i=="object"&&i!==null&&!c.startsWith("rep:")&&!c.startsWith("oak:")){const h=o?`${o}/${c}`:c;a(i,h)}}))};return s.data["jcr:content"]?a(s.data["jcr:content"],"jcr:content"):a(s.data,n),p({pagePath:n,images:r},"getPageImages")},"getPageImages")}async updateImagePath(n,t){return l(async()=>this.updateComponent({componentPath:n,properties:{fileReference:t}}),"updateImagePath")}async getPageContent(n){return l(async()=>{const s=await this.createAxiosInstance().get(`${n}.infinity.json`);return p({pagePath:n,content:s.data},"getPageContent")},"getPageContent")}async listChildren(n,t=1){return l(async()=>{const s=this.createAxiosInstance();try{const r=await s.get(`${n}.${t}.json`),a=[];return r.data&&typeof r.data=="object"&&Object.entries(r.data).forEach(([e,o])=>{if(!(e.startsWith("jcr:")||e.startsWith("sling:")||e.startsWith("cq:")||e.startsWith("rep:")||e.startsWith("oak:")||e==="jcr:content")&&o&&typeof o=="object"){const c=`${n}/${e}`;a.push({name:e,path:c,primaryType:o["jcr:primaryType"]||"nt:unstructured",title:o["jcr:content"]?.["jcr:title"]||o["jcr:title"]||e,lastModified:o["jcr:content"]?.["cq:lastModified"]||o["cq:lastModified"],resourceType:o["jcr:content"]?.["sling:resourceType"]||o["sling:resourceType"]})}}),a}catch(r){if(r.response?.status===404||r.response?.status===403)return((await s.get("/bin/querybuilder.json",{params:{path:n,type:"cq:Page","p.nodedepth":"1","p.limit":"1000","p.hits":"full"}})).data.hits||[]).map(o=>({name:o.name||o.path?.split("/").pop(),path:o.path,primaryType:o["jcr:primaryType"]||"cq:Page",title:o["jcr:content/jcr:title"]||o.title||o.name,lastModified:o["jcr:content/cq:lastModified"],resourceType:o["jcr:content/sling:resourceType"]}));throw r}},"listChildren")}async listPages(n,t=1,s=20){return l(async()=>{const r=this.createAxiosInstance();try{const a=await r.get(`${n}.${t}.json`),e=[],o=(c,i,h)=>{h>t||e.length>=s||Object.entries(c).forEach(([f,g])=>{if(!(e.length>=s)&&!(f.startsWith("jcr:")||f.startsWith("sling:")||f.startsWith("cq:")||f.startsWith("rep:")||f.startsWith("oak:"))&&g&&typeof g=="object"){const j=`${i}/${f}`;g["jcr:primaryType"]==="cq:Page"&&e.push({name:f,path:j,primaryType:"cq:Page",title:g["jcr:content"]?.["jcr:title"]||f,template:g["jcr:content"]?.["cq:template"],lastModified:g["jcr:content"]?.["cq:lastModified"],lastModifiedBy:g["jcr:content"]?.["cq:lastModifiedBy"],resourceType:g["jcr:content"]?.["sling:resourceType"],type:"page"}),h<t&&o(g,j,h+1)}})};return a.data&&typeof a.data=="object"&&o(a.data,n,0),p({siteRoot:n,pages:e,pageCount:e.length,depth:t,limit:s,totalChildrenScanned:e.length},"listPages")}catch(a){if(a.response?.status===404||a.response?.status===403){const e=await r.get("/bin/querybuilder.json",{params:{path:n,type:"cq:Page","p.nodedepth":t.toString(),"p.limit":s.toString(),"p.hits":"full"}}),o=(e.data.hits||[]).map(c=>({name:c.name||c.path?.split("/").pop(),path:c.path,primaryType:"cq:Page",title:c["jcr:content/jcr:title"]||c.title||c.name,template:c["jcr:content/cq:template"],lastModified:c["jcr:content/cq:lastModified"],lastModifiedBy:c["jcr:content/cq:lastModifiedBy"],resourceType:c["jcr:content/sling:resourceType"],type:"page"}));return p({siteRoot:n,pages:o,pageCount:o.length,depth:t,limit:s,totalChildrenScanned:e.data.total||o.length,fallbackUsed:"QueryBuilder"},"listPages")}throw a}},"listPages")}async executeJCRQuery(n,t=20){return l(async()=>{if(!n||typeof n!="string"||n.trim().length===0)throw new Error("Query is required and must be a non-empty string. Note: Only QueryBuilder fulltext is supported, not JCR SQL2.");const s=n.toLowerCase();if(/drop|delete|update|insert|exec|script|\.|<script/i.test(s)||n.length>1e3)throw new Error("Query contains potentially unsafe patterns or is too long");const a=await this.createAxiosInstance().get("/bin/querybuilder.json",{params:{path:"/content",type:"cq:Page",fulltext:n,"p.limit":t}});return{query:n,results:a.data.hits||[],total:a.data.total||0,limit:t}},"executeJCRQuery")}async getPageProperties(n){return l(async()=>{const r=(await this.createAxiosInstance().get(`${n}/jcr:content.json`)).data,a={title:r["jcr:title"],description:r["jcr:description"],template:r["cq:template"],lastModified:r["cq:lastModified"],lastModifiedBy:r["cq:lastModifiedBy"],created:r["jcr:created"],createdBy:r["jcr:createdBy"],primaryType:r["jcr:primaryType"],resourceType:r["sling:resourceType"],tags:r["cq:tags"]||[],properties:r};return p({pagePath:n,properties:a},"getPageProperties")},"getPageProperties")}async searchContent(n){return l(async()=>{const s=await this.createAxiosInstance().get(this.config.aem.endpoints.query,{params:n});return p({params:n,results:s.data.hits||[],total:s.data.total||0,rawResponse:s.data},"searchContent")},"searchContent")}async getAssetMetadata(n){return l(async()=>{const s=await this.createAxiosInstance().get(`${n}.json`),r=s.data["jcr:content"]?.metadata||{};return p({assetPath:n,metadata:r,fullData:s.data},"getAssetMetadata")},"getAssetMetadata")}async createPage(n){return l(async()=>{const{parentPath:t,title:s,template:r,name:a,properties:e}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid parent path: ${String(t)}`,{parentPath:t});const o=a||s.replace(/\s+/g,"-").toLowerCase(),c=`${t}/${o}`;return await this.createAxiosInstance().post(c,{"jcr:primaryType":"cq:Page","jcr:title":s,"cq:template":r,...e}),p({success:!0,pagePath:c,title:s,template:r,properties:e,timestamp:new Date().toISOString()},"createPage")},"createPage")}async deletePage(n){return l(async()=>{const{pagePath:t,force:s=!1}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});const r=this.createAxiosInstance();let a=!1;try{await r.delete(t),a=!0}catch(e){if(e.response&&e.response.status===405)try{await r.post("/bin/wcmcommand",{cmd:"deletePage",path:t,force:s.toString()}),a=!0}catch{try{await r.post(t,{":operation":"delete"}),a=!0}catch(c){throw console.error("Sling POST delete failed:",c.response?.status,c.response?.data),c}}else throw console.error("DELETE failed:",e.response?.status,e.response?.data),e}return p({success:a,deletedPath:t,timestamp:new Date().toISOString()},"deletePage")},"deletePage")}async createComponent(n){return l(async()=>{const{pagePath:t,componentPath:s,componentType:r,resourceType:a,properties:e={},name:o}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});const c=o||`${r}_${Date.now()}`,i=s||`${t}/jcr:content/${c}`;return await this.createAxiosInstance().post(i,{"jcr:primaryType":"nt:unstructured","sling:resourceType":a,...e,":operation":"import",":contentType":"json",":replace":"true"}),p({success:!0,componentPath:s,componentType:r,resourceType:a,properties:e,timestamp:new Date().toISOString()},"createComponent")},"createComponent")}async deleteComponent(n){return l(async()=>{const{componentPath:t,force:s=!1}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid component path: ${String(t)}`,{componentPath:t});const r=this.createAxiosInstance();let a=!1;try{await r.delete(t),a=!0}catch(e){if(e.response&&e.response.status===405)try{await r.post(t,{":operation":"delete"}),a=!0}catch(o){throw console.error("Sling POST delete failed:",o.response?.status,o.response?.data),o}else throw console.error("DELETE failed:",e.response?.status,e.response?.data),e}return p({success:a,deletedPath:t,timestamp:new Date().toISOString()},"deleteComponent")},"deleteComponent")}async unpublishContent(n){return l(async()=>{const{contentPaths:t,unpublishTree:s=!1}=n;if(!t||Array.isArray(t)&&t.length===0)throw d(m.INVALID_PARAMETERS,"Content paths array is required and cannot be empty",{contentPaths:t});const r=this.createAxiosInstance(),a=[];for(const e of Array.isArray(t)?t:[t])try{const o=new URLSearchParams;o.append("cmd","Deactivate"),o.append("path",e),o.append("ignoredeactivated","false"),o.append("onlymodified","false"),s&&o.append("deep","true");const c=await r.post("/bin/replicate.json",o,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});a.push({path:e,success:!0,response:c.data})}catch(o){a.push({path:e,success:!1,error:o.response?.data||o.message})}return p({success:a.every(e=>e.success),results:a,unpublishedPaths:t,unpublishTree:s,timestamp:new Date().toISOString()},"unpublishContent")},"unpublishContent")}async activatePage(n){return l(async()=>{const{pagePath:t,activateTree:s=!1}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});const r=this.createAxiosInstance();try{const a=new URLSearchParams;a.append("cmd","Activate"),a.append("path",t),a.append("ignoredeactivated","false"),a.append("onlymodified","false"),s&&a.append("deep","true");const e=await r.post("/bin/replicate.json",a,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});return p({success:!0,activatedPath:t,activateTree:s,response:e.data,timestamp:new Date().toISOString()},"activatePage")}catch(a){try{const e=await r.post("/bin/wcmcommand",{cmd:"activate",path:t,ignoredeactivated:!1,onlymodified:!1});return p({success:!0,activatedPath:t,activateTree:s,response:e.data,fallbackUsed:"WCM Command",timestamp:new Date().toISOString()},"activatePage")}catch{throw y(a,"activatePage")}}},"activatePage")}async deactivatePage(n){return l(async()=>{const{pagePath:t,deactivateTree:s=!1}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});const r=this.createAxiosInstance();try{const a=new URLSearchParams;a.append("cmd","Deactivate"),a.append("path",t),a.append("ignoredeactivated","false"),a.append("onlymodified","false"),s&&a.append("deep","true");const e=await r.post("/bin/replicate.json",a,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});return p({success:!0,deactivatedPath:t,deactivateTree:s,response:e.data,timestamp:new Date().toISOString()},"deactivatePage")}catch(a){try{const e=await r.post("/bin/wcmcommand",{cmd:"deactivate",path:t,ignoredeactivated:!1,onlymodified:!1});return p({success:!0,deactivatedPath:t,deactivateTree:s,response:e.data,fallbackUsed:"WCM Command",timestamp:new Date().toISOString()},"deactivatePage")}catch{throw y(a,"deactivatePage")}}},"deactivatePage")}async uploadAsset(n){return l(async()=>{const{parentPath:t,fileName:s,fileContent:r,mimeType:a,metadata:e={}}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid parent path: ${String(t)}`,{parentPath:t});const o=this.createAxiosInstance(),c=`${t}/${s}`;try{const i=new URLSearchParams;typeof r=="string"?i.append("file",r):i.append("file",r.toString()),i.append("fileName",s),i.append(":operation","import"),i.append(":contentType","json"),i.append(":replace","true"),i.append("jcr:primaryType","dam:Asset"),a&&i.append("jcr:content/jcr:mimeType",a),Object.entries(e).forEach(([g,j])=>{i.append(`jcr:content/metadata/${g}`,String(j))});const h=await o.post(c,i,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),f=await o.get(`${c}.json`);return p({success:!0,assetPath:c,fileName:s,mimeType:a,metadata:e,uploadResponse:h.data,assetData:f.data,timestamp:new Date().toISOString()},"uploadAsset")}catch(i){try{const h=await o.post("/api/assets"+t,{fileName:s,fileContent:r,mimeType:a,metadata:e});return p({success:!0,assetPath:c,fileName:s,mimeType:a,metadata:e,uploadResponse:h.data,fallbackUsed:"DAM API",timestamp:new Date().toISOString()},"uploadAsset")}catch{throw y(i,"uploadAsset")}}},"uploadAsset")}async updateAsset(n){return l(async()=>{const{assetPath:t,metadata:s,fileContent:r,mimeType:a}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid asset path: ${String(t)}`,{assetPath:t});const e=this.createAxiosInstance(),o=new URLSearchParams;r&&(o.append("file",r),a&&o.append("jcr:content/jcr:mimeType",a)),s&&typeof s=="object"&&Object.entries(s).forEach(([c,i])=>{o.append(`jcr:content/metadata/${c}`,String(i))});try{const c=await e.post(t,o,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),i=await e.get(`${t}.json`);return p({success:!0,assetPath:t,updatedMetadata:s,updateResponse:c.data,assetData:i.data,timestamp:new Date().toISOString()},"updateAsset")}catch(c){throw y(c,"updateAsset")}},"updateAsset")}async deleteAsset(n){return l(async()=>{const{assetPath:t,force:s=!1}=n;if(!u(t,this.aemConfig))throw d(m.INVALID_PARAMETERS,`Invalid asset path: ${String(t)}`,{assetPath:t});return await this.createAxiosInstance().delete(t),p({success:!0,deletedPath:t,force:s,timestamp:new Date().toISOString()},"deleteAsset")},"deleteAsset")}async getTemplates(n){return l(async()=>{const t=this.createAxiosInstance();if(n)try{const s=`/conf${n.replace("/content","")}/settings/wcm/templates`,r=await t.get(`${s}.json`,{params:{":depth":"2"}}),a=[];return r.data&&typeof r.data=="object"&&Object.entries(r.data).forEach(([e,o])=>{e.startsWith("jcr:")||e.startsWith("sling:")||o&&typeof o=="object"&&o["jcr:content"]&&a.push({name:e,path:`${s}/${e}`,title:o["jcr:content"]["jcr:title"]||e,description:o["jcr:content"]["jcr:description"],allowedPaths:o["jcr:content"].allowedPaths,ranking:o["jcr:content"].ranking||0})}),p({sitePath:n,templates:a,totalCount:a.length,source:"site-specific"},"getTemplates")}catch{}try{const s=["/apps/wcm/core/content/sites/templates","/libs/wcm/core/content/sites/templates"],r=[];for(const a of s)try{const e=await t.get(`${a}.json`,{params:{":depth":"2"}});e.data&&typeof e.data=="object"&&Object.entries(e.data).forEach(([o,c])=>{o.startsWith("jcr:")||o.startsWith("sling:")||c&&typeof c=="object"&&r.push({name:o,path:`${a}/${o}`,title:c["jcr:content"]?.["jcr:title"]||o,description:c["jcr:content"]?.["jcr:description"],allowedPaths:c["jcr:content"]?.allowedPaths,ranking:c["jcr:content"]?.ranking||0,source:a.includes("/apps/")?"apps":"libs"})})}catch{}return p({sitePath:n||"global",templates:r,totalCount:r.length,source:"global"},"getTemplates")}catch(s){throw y(s,"getTemplates")}},"getTemplates")}async getTemplateStructure(n){return l(async()=>{const t=this.createAxiosInstance();try{const s=await t.get(`${n}.infinity.json`),r={path:n,properties:s.data["jcr:content"]||{},policies:s.data["jcr:content"]?.policies||{},structure:s.data["jcr:content"]?.structure||{},initialContent:s.data["jcr:content"]?.initial||{},allowedComponents:[],allowedPaths:s.data["jcr:content"]?.allowedPaths||[]},a=(e,o="")=>{if(!(!e||typeof e!="object")){if(e.components){const c=Object.keys(e.components);r.allowedComponents.push(...c)}Object.entries(e).forEach(([c,i])=>{typeof i=="object"&&i!==null&&!c.startsWith("jcr:")&&a(i,o?`${o}/${c}`:c)})}};return a(r.policies),r.allowedComponents=[...new Set(r.allowedComponents)],p({templatePath:n,structure:r,fullData:s.data},"getTemplateStructure")}catch(s){throw y(s,"getTemplateStructure")}},"getTemplateStructure")}async bulkUpdateComponents(n){return l(async()=>{const{updates:t,validateFirst:s=!0,continueOnError:r=!1}=n;if(!Array.isArray(t)||t.length===0)throw d(m.INVALID_PARAMETERS,"Updates array is required and cannot be empty");const a=[],e=this.createAxiosInstance();if(s)for(const c of t)try{await e.get(`${c.componentPath}.json`)}catch(i){if(i.response?.status===404&&(a.push({componentPath:c.componentPath,success:!1,error:`Component not found: ${c.componentPath}`,phase:"validation"}),!r))return p({success:!1,message:"Bulk update failed during validation phase",results:a,totalUpdates:t.length,successfulUpdates:0},"bulkUpdateComponents")}let o=0;for(const c of t)try{const i=await this.updateComponent({componentPath:c.componentPath,properties:c.properties});a.push({componentPath:c.componentPath,success:!0,result:i,phase:"update"}),o++}catch(i){if(a.push({componentPath:c.componentPath,success:!1,error:i.message,phase:"update"}),!r)break}return p({success:o===t.length,message:`Bulk update completed: ${o}/${t.length} successful`,results:a,totalUpdates:t.length,successfulUpdates:o,failedUpdates:t.length-o},"bulkUpdateComponents")},"bulkUpdateComponents")}async getNodeContent(n,t=1){return l(async()=>{const r=await this.createAxiosInstance().get(`${n}.json`,{params:{":depth":t.toString()}});return{path:n,depth:t,content:r.data,timestamp:new Date().toISOString()}},"getNodeContent")}}
1
+ "use strict";import{getAEMConfig as j,isValidContentPath as g,isValidLocale as P}from"./aem.config.js";import{AEM_ERROR_CODES as h,createAEMError as d,createSuccessResponse as i,handleAEMHttpError as u,safeExecute as p,validateComponentOperation as b}from"./aem.errors.js";import{AEMFetch as w}from"./aem.fetch.js";export class AEMConnector{isInitialized;config;aemConfig;fetch;constructor(e){this.isInitialized=!1,this.config=this.loadConfig(e),this.aemConfig=j({}),this.fetch=new w({host:this.config.aem.host,username:this.config.aem.serviceUser.username,password:this.config.aem.serviceUser.password,timeout:this.aemConfig.queries.timeoutMs})}async init(){try{await this.fetch.init(),this.isInitialized=!0}catch{this.isInitialized=!1}}loadConfig(e={}){return{aem:{host:e.host||"http://localhost:4502",author:e.host||"http://localhost:4502",publish:"http://localhost:4503",serviceUser:{username:e.user||"admin",password:e.pass||"admin"},endpoints:{content:"/content",dam:"/content/dam",query:"/bin/querybuilder.json",crxde:"/crx/de",jcr:""}},mcp:{name:"AEM MCP Server",version:"1.0.0"}}}async testConnection(){try{console.log("Testing AEM connection to:",this.config.aem.host);const e=`${this.config.aem.host}/libs/granite/core/content/login.html`,t=await this.fetch.get(e,{timeout:5e3});return console.log("\u2705 AEM connection successful! Status:",t.status),!0}catch(e){return console.error("\u274C AEM connection failed:",e.message),!1}}async validateComponent(e){return p(async()=>{const t=e.pagePath||e.page_path,{locale:n,component:s,props:a}=e;if(b(n,t,s,a),!P(n,this.aemConfig))throw d(h.INVALID_LOCALE,`Locale '${n}' is not supported`,{locale:n,allowedLocales:this.aemConfig.validation.allowedLocales});if(!g(t,this.aemConfig))throw d(h.INVALID_PATH,`Path '${t}' is not within allowed content roots`,{path:t,allowedRoots:Object.values(this.aemConfig.contentPaths)});const r=`${t}.json`,o=await this.fetch.get(r,{params:{":depth":"2"},timeout:this.aemConfig.queries.timeoutMs}),c=this.validateComponentProps(o.data,s,a);return i({message:"Component validation completed successfully",pageData:o.data,component:s,locale:n,validation:c,configUsed:{allowedLocales:this.aemConfig.validation.allowedLocales}},"validateComponent")},"validateComponent")}validateComponentProps(e,t,n){const s=[],a=[];return t==="text"&&!n.text&&!n.richText&&s.push("Text component should have text or richText property"),t==="image"&&!n.fileReference&&!n.src&&a.push("Image component requires fileReference or src property"),{valid:a.length===0,errors:a,warnings:s,componentType:t,propsValidated:Object.keys(n).length}}async updateComponent(e){return p(async()=>{if(!e.componentPath||typeof e.componentPath!="string")throw d(h.INVALID_PARAMETERS,"Component path is required and must be a string");if(!e.properties||typeof e.properties!="object")throw d(h.INVALID_PARAMETERS,"Properties are required and must be an object");if(!g(e.componentPath,this.aemConfig))throw d(h.INVALID_PATH,`Component path '${e.componentPath}' is not within allowed content roots`,{path:e.componentPath,allowedRoots:Object.values(this.aemConfig.contentPaths)});const t=`${e.componentPath}.json`,n=await this.fetch.get(t);try{await n.json()}catch(o){throw o.response?.status===404?d(h.COMPONENT_NOT_FOUND,`Component not found at path: ${e.componentPath}`,{componentPath:e.componentPath}):u(o,"updateComponent")}const s=new URLSearchParams;Object.entries(e.properties).forEach(([o,c])=>{c==null?s.append(`${o}@Delete`,""):Array.isArray(c)?c.forEach(l=>{s.append(`${o}`,l.toString())}):typeof c=="object"?s.append(o,JSON.stringify(c)):s.append(o,c.toString())});const a=await this.fetch.post(e.componentPath,s),r=await this.fetch.get(`${e.componentPath}.json`);return i({message:"Component updated successfully",path:e.componentPath,properties:e.properties,updatedProperties:r.data,response:a.data,verification:{success:!0,propertiesChanged:Object.keys(e.properties).length,timestamp:new Date().toISOString()}},"updateComponent")},"updateComponent")}async undoChanges(e){return i({message:"undoChanges is not implemented. Please use AEM version history for undo/rollback.",request:e,timestamp:new Date().toISOString()},"undoChanges")}async scanPageComponents(e){return p(async()=>{const t=`${e}.infinity.json`,n=await this.fetch.get(t),s=[],a=(r,o)=>{!r||typeof r!="object"||(r["sling:resourceType"]&&s.push({path:o,resourceType:r["sling:resourceType"],properties:{...r}}),Object.entries(r).forEach(([c,l])=>{if(typeof l=="object"&&l!==null&&!c.startsWith("rep:")&&!c.startsWith("oak:")){const m=o?`${o}/${c}`:c;a(l,m)}}))};return n.data["jcr:content"]?a(n.data["jcr:content"],"jcr:content"):a(n.data,e),i({pagePath:e,components:s,totalComponents:s.length},"scanPageComponents")},"scanPageComponents")}async fetchSites(){return p(async()=>{const t=await this.fetch.get("/content.json",{":depth":"2"}),n=[];return Object.entries(t).forEach(([s,a])=>{s.startsWith("jcr:")||s.startsWith("sling:")||a&&typeof a=="object"&&a["jcr:content"]&&n.push({name:s,path:`/content/${s}`,title:a["jcr:content"]["jcr:title"]||s,template:a["jcr:content"]["cq:template"],lastModified:a["jcr:content"]["cq:lastModified"]})}),i({sites:n,totalCount:n.length},"fetchSites")},"fetchSites")}async fetchLanguageMasters(e){return p(async()=>{const t=`/content/${e}.json`,n=await this.fetch.get(t,{":depth":"3"}),s=[];return Object.entries(n).forEach(([a,r])=>{a.startsWith("jcr:")||a.startsWith("sling:")||r&&typeof r=="object"&&r["jcr:content"]&&s.push({name:a,path:`/content/${a}`,title:r["jcr:content"]["jcr:title"]||a,language:r["jcr:content"]["jcr:language"]||"en"})}),i({site:e,languageMasters:s},"fetchLanguageMasters")},"fetchLanguageMasters")}async fetchAvailableLocales(e,t){return p(async()=>{const n=`${t}.json`,s=await this.fetch.get(n,{":depth":"2"}),a=[];return Object.entries(s).forEach(([r,o])=>{r.startsWith("jcr:")||r.startsWith("sling:")||o&&typeof o=="object"&&a.push({name:r,title:o["jcr:content"]?.["jcr:title"]||r,language:o["jcr:content"]?.["jcr:language"]||r})}),i({site:e,languageMasterPath:t,availableLocales:a},"fetchAvailableLocales")},"fetchAvailableLocales")}async replicateAndPublish(e,t,n){return p(async()=>i({message:"Replication simulated",selectedLocales:e,componentData:t,localizedOverrides:n},"replicateAndPublish"),"replicateAndPublish")}async getAllTextContent(e){return p(async()=>{const t=`${e}.infinity.json`,n=await this.fetch.get(t),s=[],a=(r,o)=>{!r||typeof r!="object"||((r.text||r["jcr:title"]||r["jcr:description"])&&s.push({path:o,title:r["jcr:title"],text:r.text,description:r["jcr:description"]}),Object.entries(r).forEach(([c,l])=>{if(typeof l=="object"&&l!==null&&!c.startsWith("rep:")&&!c.startsWith("oak:")){const m=o?`${o}/${c}`:c;a(l,m)}}))};return n["jcr:content"]?a(n["jcr:content"],"jcr:content"):a(n,e),i({pagePath:e,textContent:s},"getAllTextContent")},"getAllTextContent")}async getPageTextContent(e){return p(async()=>this.getAllTextContent(e),"getPageTextContent")}async getPageImages(e){return p(async()=>{const t=`${e}.infinity.json`,n=await this.fetch.get(t),s=[],a=(r,o)=>{!r||typeof r!="object"||((r.fileReference||r.src)&&s.push({path:o,fileReference:r.fileReference,src:r.src,alt:r.alt||r.altText,title:r["jcr:title"]||r.title}),Object.entries(r).forEach(([c,l])=>{if(typeof l=="object"&&l!==null&&!c.startsWith("rep:")&&!c.startsWith("oak:")){const m=o?`${o}/${c}`:c;a(l,m)}}))};return n["jcr:content"]?a(n["jcr:content"],"jcr:content"):a(n,e),i({pagePath:e,images:s},"getPageImages")},"getPageImages")}async updateImagePath(e,t){return p(async()=>this.updateComponent({componentPath:e,properties:{fileReference:t}}),"updateImagePath")}async getPageContent(e){return p(async()=>{const t=`${e}.infinity.json`,n=await this.fetch.get(t);return i({pagePath:e,content:n},"getPageContent")},"getPageContent")}async listChildren(e,t=1){return p(async()=>{try{const n=await this.fetch.get(`${e}.${t}.json`),s=[];return n&&typeof n=="object"&&Object.entries(n).forEach(([a,r])=>{if(!(a.startsWith("jcr:")||a.startsWith("sling:")||a.startsWith("cq:")||a.startsWith("rep:")||a.startsWith("oak:")||a==="jcr:content")&&r&&typeof r=="object"){const o=`${e}/${a}`;s.push({name:a,path:o,primaryType:r["jcr:primaryType"]||"nt:unstructured",title:r["jcr:content"]?.["jcr:title"]||r["jcr:title"]||a,lastModified:r["jcr:content"]?.["cq:lastModified"]||r["cq:lastModified"],resourceType:r["jcr:content"]?.["sling:resourceType"]||r["sling:resourceType"]})}}),s}catch(n){if(n.response?.status===404||n.response?.status===403)return((await this.fetch.get("/bin/querybuilder.json",{path:e,type:"cq:Page","p.nodedepth":"1","p.limit":"1000","p.hits":"full"})).hits||[]).map(a=>({name:a.name||a.path?.split("/").pop(),path:a.path,primaryType:a["jcr:primaryType"]||"cq:Page",title:a["jcr:content/jcr:title"]||a.title||a.name,lastModified:a["jcr:content/cq:lastModified"],resourceType:a["jcr:content/sling:resourceType"]}));throw n}},"listChildren")}async listPages(e,t=1,n=20){return p(async()=>{try{const s=await this.fetch.get(`${e}.${t}.json`),a=[],r=(o,c,l)=>{l>t||a.length>=n||Object.entries(o).forEach(([m,f])=>{if(!(a.length>=n)&&!(m.startsWith("jcr:")||m.startsWith("sling:")||m.startsWith("cq:")||m.startsWith("rep:")||m.startsWith("oak:"))&&f&&typeof f=="object"){const y=`${c}/${m}`;f["jcr:primaryType"]==="cq:Page"&&a.push({name:m,path:y,primaryType:"cq:Page",title:f["jcr:content"]?.["jcr:title"]||m,template:f["jcr:content"]?.["cq:template"],lastModified:f["jcr:content"]?.["cq:lastModified"],lastModifiedBy:f["jcr:content"]?.["cq:lastModifiedBy"],resourceType:f["jcr:content"]?.["sling:resourceType"],type:"page"}),l<t&&r(f,y,l+1)}})};return s&&typeof s=="object"&&r(s,e,0),i({siteRoot:e,pages:a,pageCount:a.length,depth:t,limit:n,totalChildrenScanned:a.length},"listPages")}catch(s){if(console.warn("JSON API failed, falling back to QueryBuilder:",s.message),s.response?.status===404||s.response?.status===403){const a=await this.fetch.get("/bin/querybuilder.json",{path:e,type:"cq:Page","p.nodedepth":t.toString(),"p.limit":n.toString(),"p.hits":"full"}),r=(a.hits||[]).map(o=>({name:o.name||o.path?.split("/").pop(),path:o.path,primaryType:"cq:Page",title:o["jcr:content/jcr:title"]||o.title||o.name,template:o["jcr:content/cq:template"],lastModified:o["jcr:content/cq:lastModified"],lastModifiedBy:o["jcr:content/cq:lastModifiedBy"],resourceType:o["jcr:content/sling:resourceType"],type:"page"}));return i({siteRoot:e,pages:r,pageCount:r.length,depth:t,limit:n,totalChildrenScanned:a.total||r.length,fallbackUsed:"QueryBuilder"},"listPages")}throw s}},"listPages")}async executeJCRQuery(e,t=20){return p(async()=>{if(!e||e.trim().length===0)throw new Error("Query is required and must be a non-empty string. Note: Only QueryBuilder fulltext is supported, not JCR SQL2.");const n=e.toLowerCase();if(/drop|delete|update|insert|exec|script|\.|<script/i.test(n)||e.length>1e3)throw new Error("Query contains potentially unsafe patterns or is too long");const s=await this.fetch.get("/bin/querybuilder.json",{path:"/content",type:"cq:Page",fulltext:e,"p.limit":t});return{query:e,results:s.hits||[],total:s.total||0,limit:t}},"executeJCRQuery")}async getPageProperties(e){return p(async()=>{const t=`${e}/jcr:content.json`,n=await this.fetch.get(t),s={title:n["jcr:title"],description:n["jcr:description"],template:n["cq:template"],lastModified:n["cq:lastModified"],lastModifiedBy:n["jcr:createdBy"],created:n["jcr:created"],createdBy:n["jcr:createdBy"],primaryType:n["jcr:primaryType"],resourceType:n["sling:resourceType"],tags:n["cq:tags"]||[],properties:n};return i({pagePath:e,properties:s},"getPageProperties")},"getPageProperties")}async searchContent(e){return p(async()=>{const t=await this.fetch.get(this.config.aem.endpoints.query,e);return i({params:e,results:t.hits||[],total:t.total||0,rawResponse:t},"searchContent")},"searchContent")}async getAssetMetadata(e){return p(async()=>{const t=`${e}.json`,n=await this.fetch.get(t),s=n["jcr:content"]?.metadata||{};return i({assetPath:e,metadata:s,fullData:n},"getAssetMetadata")},"getAssetMetadata")}async createPage(e){return p(async()=>{const{parentPath:t,title:n,template:s,name:a,properties:r}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid parent path: ${String(t)}`,{parentPath:t});const o=a||n.replace(/\s+/g,"-").toLowerCase(),c=`${t}/${o}`;return await this.fetch.post(c,{"jcr:primaryType":"cq:Page","jcr:title":n,"cq:template":s,...r}),i({success:!0,pagePath:c,title:n,template:s,properties:r,timestamp:new Date().toISOString()},"createPage")},"createPage")}async deletePage(e){return p(async()=>{const{pagePath:t}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});let n=!1;try{await this.fetch.delete(t),n=!0}catch{try{await this.fetch.post("/bin/wcmcommand",{cmd:"deletePage",path:t,force:e.force?"true":"false"}),n=!0}catch{try{await this.fetch.post(t,{":operation":"delete"}),n=!0}catch(r){throw r}}}return i({success:n,deletedPath:t,timestamp:new Date().toISOString()},"deletePage")},"deletePage")}async createComponent(e){return p(async()=>{const{pagePath:t,componentPath:n,componentType:s,resourceType:a,properties:r={},name:o}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});const c=o||`${s}_${Date.now()}`,l=n||`${t}/jcr:content/${c}`;return await this.fetch.post(l,{"jcr:primaryType":"nt:unstructured","sling:resourceType":a,...r,":operation":"import",":contentType":"json",":replace":"true"}),i({success:!0,componentPath:l,componentType:s,resourceType:a,properties:r,timestamp:new Date().toISOString()},"createComponent")},"createComponent")}async deleteComponent(e){return p(async()=>{const{componentPath:t}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid component path: ${String(t)}`,{componentPath:t});let n=!1;try{await this.fetch.delete(t),n=!0}catch{try{await this.fetch.post(t,{":operation":"delete"}),n=!0}catch(a){throw a}}return i({success:n,deletedPath:t,timestamp:new Date().toISOString()},"deleteComponent")},"deleteComponent")}async unpublishContent(e){return p(async()=>{const{contentPaths:t,unpublishTree:n=!1}=e;if(!t||Array.isArray(t)&&t.length===0)throw d(h.INVALID_PARAMETERS,"Content paths array is required and cannot be empty",{contentPaths:t});const s=[];for(const a of Array.isArray(t)?t:[t])try{const r=new URLSearchParams;r.append("cmd","Deactivate"),r.append("path",a),r.append("ignoredeactivated","false"),r.append("onlymodified","false"),n&&r.append("deep","true");const o=await this.fetch.post("/bin/replicate.json",r);s.push({path:a,success:!0,response:o})}catch(r){s.push({path:a,success:!1,error:r.message})}return i({success:s.every(a=>a.success),results:s,unpublishedPaths:t,unpublishTree:n,timestamp:new Date().toISOString()},"unpublishContent")},"unpublishContent")}async activatePage(e){return p(async()=>{const{pagePath:t,activateTree:n=!1}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});try{const s=new URLSearchParams;s.append("cmd","Activate"),s.append("path",t),s.append("ignoredeactivated","false"),s.append("onlymodified","false"),n&&s.append("deep","true");const a=await this.fetch.post("/bin/replicate.json",s);return i({success:!0,activatedPath:t,activateTree:n,response:a,timestamp:new Date().toISOString()},"activatePage")}catch(s){try{const a=await this.fetch.post("/bin/wcmcommand",{cmd:"activate",path:t,ignoredeactivated:!1,onlymodified:!1});return i({success:!0,activatedPath:t,activateTree:n,response:a,fallbackUsed:"WCM Command",timestamp:new Date().toISOString()},"activatePage")}catch{throw u(s,"activatePage")}}},"activatePage")}async deactivatePage(e){return p(async()=>{const{pagePath:t,deactivateTree:n=!1}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid page path: ${String(t)}`,{pagePath:t});try{const s=new URLSearchParams;s.append("cmd","Deactivate"),s.append("path",t),s.append("ignoredeactivated","false"),s.append("onlymodified","false"),n&&s.append("deep","true");const a=await this.fetch.post("/bin/replicate.json",s);return i({success:!0,deactivatedPath:t,deactivateTree:n,response:a,timestamp:new Date().toISOString()},"deactivatePage")}catch(s){try{const a=await this.fetch.post("/bin/wcmcommand",{cmd:"deactivate",path:t,ignoredeactivated:!1,onlymodified:!1});return i({success:!0,deactivatedPath:t,deactivateTree:n,response:a,fallbackUsed:"WCM Command",timestamp:new Date().toISOString()},"deactivatePage")}catch{throw u(s,"deactivatePage")}}},"deactivatePage")}async uploadAsset(e){return p(async()=>{const{parentPath:t,fileName:n,fileContent:s,mimeType:a,metadata:r={}}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid parent path: ${String(t)}`,{parentPath:t});const o=`${t}/${n}`;try{const c=new URLSearchParams;typeof s=="string"?c.append("file",s):c.append("file",s.toString()),c.append("fileName",n),c.append(":operation","import"),c.append(":contentType","json"),c.append(":replace","true"),c.append("jcr:primaryType","dam:Asset"),a&&c.append("jcr:content/jcr:mimeType",a),Object.entries(r).forEach(([f,y])=>{c.append(`jcr:content/metadata/${f}`,String(y))});const l=await this.fetch.post(o,c),m=await this.fetch.get(`${o}.json`);return i({success:!0,assetPath:o,fileName:n,mimeType:a,metadata:r,uploadResponse:l,assetData:m,timestamp:new Date().toISOString()},"uploadAsset")}catch(c){try{const l=await this.fetch.post("/api/assets"+t,{fileName:n,fileContent:s,mimeType:a,metadata:r});return i({success:!0,assetPath:o,fileName:n,mimeType:a,metadata:r,uploadResponse:l,fallbackUsed:"DAM API",timestamp:new Date().toISOString()},"uploadAsset")}catch{throw u(c,"uploadAsset")}}},"uploadAsset")}async updateAsset(e){return p(async()=>{const{assetPath:t,metadata:n,fileContent:s,mimeType:a}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid asset path: ${String(t)}`,{assetPath:t});const r=new URLSearchParams;s&&(r.append("file",s),a&&r.append("jcr:content/jcr:mimeType",a)),n&&typeof n=="object"&&Object.entries(n).forEach(([o,c])=>{r.append(`jcr:content/metadata/${o}`,String(c))});try{const o=await this.fetch.post(t,r),c=await this.fetch.get(`${t}.json`);return i({success:!0,assetPath:t,updatedMetadata:n,updateResponse:o,assetData:c,timestamp:new Date().toISOString()},"updateAsset")}catch(o){throw u(o,"updateAsset")}},"updateAsset")}async deleteAsset(e){return p(async()=>{const{assetPath:t,force:n=!1}=e;if(!g(t,this.aemConfig))throw d(h.INVALID_PARAMETERS,`Invalid asset path: ${String(t)}`,{assetPath:t});return await this.fetch.delete(t),i({success:!0,deletedPath:t,force:n,timestamp:new Date().toISOString()},"deleteAsset")},"deleteAsset")}async getTemplateStructure(e){return p(async()=>{try{const t=await this.fetch.get(`${e}.infinity.json`),n={path:e,properties:t["jcr:content"]||{},policies:t["jcr:content"]?.policies||{},structure:t["jcr:content"]?.structure||{},initialContent:t["jcr:content"]?.initial||{},allowedComponents:[],allowedPaths:t["jcr:content"]?.allowedPaths||[]},s=(a,r="")=>{if(!(!a||typeof a!="object")){if(a.components){const o=Object.keys(a.components);n.allowedComponents.push(...o)}Object.entries(a).forEach(([o,c])=>{typeof c=="object"&&c!==null&&!o.startsWith("jcr:")&&s(c,r?`${r}/${o}`:o)})}};return s(n.policies),n.allowedComponents=[...new Set(n.allowedComponents)],i({templatePath:e,structure:n,fullData:t},"getTemplateStructure")}catch(t){throw u(t,"getTemplateStructure")}},"getTemplateStructure")}async bulkUpdateComponents(e){return p(async()=>{const{updates:t,validateFirst:n=!0,continueOnError:s=!1}=e;if(!Array.isArray(t)||t.length===0)throw d(h.INVALID_PARAMETERS,"Updates array is required and cannot be empty");const a=[];if(n)for(const o of t)try{await this.fetch.get(`${o.componentPath}.json`)}catch(c){if(c.response?.status===404&&(a.push({componentPath:o.componentPath,success:!1,error:`Component not found: ${o.componentPath}`,phase:"validation"}),!s))return i({success:!1,message:"Bulk update failed during validation phase",results:a,totalUpdates:t.length,successfulUpdates:0},"bulkUpdateComponents")}let r=0;for(const o of t)try{const c=await this.updateComponent({componentPath:o.componentPath,properties:o.properties});a.push({componentPath:o.componentPath,success:!0,result:c,phase:"update"}),r++}catch(c){if(a.push({componentPath:o.componentPath,success:!1,error:c.message,phase:"update"}),!s)break}return i({success:r===t.length,message:`Bulk update completed: ${r}/${t.length} successful`,results:a,totalUpdates:t.length,successfulUpdates:r,failedUpdates:t.length-r},"bulkUpdateComponents")},"bulkUpdateComponents")}async getNodeContent(e,t=1){return p(async()=>{const n=`${e}.json`,s=await this.fetch.get(n,{":depth":t.toString()});return{path:e,depth:t,content:s,timestamp:new Date().toISOString()}},"getNodeContent")}}
@@ -0,0 +1 @@
1
+ "use strict";import{getAccessToken as c}from"./aem.auth.js";export class AEMFetch{fetch;config;constructor(t){this.config=t,this.fetch=null}async init(){const t=await this.getAuthToken(this.config);this.fetch=this.getFetchInstance(t)}getFetchInstance(t){return(e,s={})=>{const n=new Headers(s.headers||{});return n.set("Authorization",`Basic ${t}`),n.set("Accept","application/json"),n.has("Content-Type")||n.set("Content-Type","application/json"),fetch(e,{...s,headers:n})}}async getAuthToken(t){if(t.clientId&&t.clientSecret)return c(t.clientId,t.clientSecret,t.scope);if(t.username&&t.password)return Buffer.from(`${t.username}:${t.password}`).toString("base64");throw new Error("No authentication credentials provided")}getTimeoutOptions(t){let e,s,n;const i=t||this.config.timeout;return i&&(e=new AbortController,n=e.signal,s=setTimeout(()=>e.abort(),i)),{signal:n,timeoutId:s}}buildUrlWithParams(t,e){const s=this.config.host.endsWith("/")?this.config.host.slice(0,-1):this.config.host,n=t.startsWith("/")?t:`/${t}`,i=`${s}${n}`;if(!e||Object.keys(e).length===0)return i;const r=new URL(i);return Object.entries(e).forEach(([o,a])=>{a!=null&&r.searchParams.append(o,String(a))}),r.toString()}async request(t,e={},s){if(!this.fetch)throw new Error("AEMFetch not initialized. Call await init(config) before making requests.");const{timeoutId:n,signal:i}=this.getTimeoutOptions(s);s&&(e.signal=i);let r;try{if(r=await this.fetch(t,e),r.status===401){console.warn(`AEM request to ${t} returned 401 Unauthorized. Attempting to refresh token...`);const o=await this.getAuthToken(this.config);this.fetch=this.getFetchInstance(o),r=await this.fetch(t,e)}if(!r.ok)throw new Error(`AEM ${e.method||"GET"} failed: ${r.status}`);return r.json()}finally{n&&clearTimeout(n)}}async get(t,e,s={},n){const i=this.buildUrlWithParams(t,e);return this.request(i,s,n)}async post(t,e,s={},n){let i,r=new Headers(s.headers||{});e instanceof URLSearchParams?(i=e,r.set("Content-Type","application/x-www-form-urlencoded")):(i=JSON.stringify(e),r.set("Content-Type","application/json"));const o=this.buildUrlWithParams(t);return this.request(o,{...s,method:"POST",body:i,headers:r},n)}async delete(t,e={},s){const n=this.buildUrlWithParams(t);return this.request(n,{...e,method:"DELETE"},s)}}
@@ -1 +1 @@
1
- "use strict";import{config as a}from"../config.js";export class MCPRequestHandler{aemConnector;config;constructor(t,e){this.config=t,this.aemConnector=e}async handleRequest(t,e){try{switch(t){case"validateComponent":return await this.aemConnector.validateComponent(e);case"updateComponent":return await this.aemConnector.updateComponent(e);case"undoChanges":return await this.aemConnector.undoChanges(e);case"scanPageComponents":return await this.aemConnector.scanPageComponents(e.pagePath);case"fetchSites":return await this.aemConnector.fetchSites();case"fetchLanguageMasters":return await this.aemConnector.fetchLanguageMasters(e.site);case"fetchAvailableLocales":return await this.aemConnector.fetchAvailableLocales(e.site,e.languageMasterPath);case"replicateAndPublish":return await this.aemConnector.replicateAndPublish(e.selectedLocales,e.componentData,e.localizedOverrides);case"getAllTextContent":return await this.aemConnector.getAllTextContent(e.pagePath);case"getPageTextContent":return await this.aemConnector.getPageTextContent(e.pagePath);case"getPageImages":return await this.aemConnector.getPageImages(e.pagePath);case"updateImagePath":return await this.aemConnector.updateImagePath(e.componentPath,e.newImagePath);case"getPageContent":return await this.aemConnector.getPageContent(e.pagePath);case"listPages":return await this.aemConnector.listPages(e.siteRoot||e.path||"/content",e.depth||1,e.limit||20);case"getNodeContent":return await this.aemConnector.getNodeContent(e.path,e.depth||1);case"listChildren":return await this.aemConnector.listChildren(e.path);case"getPageProperties":return await this.aemConnector.getPageProperties(e.pagePath);case"searchContent":return await this.aemConnector.searchContent(e);case"executeJCRQuery":return await this.aemConnector.executeJCRQuery(e.query,e.limit);case"getAssetMetadata":return await this.aemConnector.getAssetMetadata(e.assetPath);case"getStatus":return this.getWorkflowStatus(e.workflowId);case"enhancedPageSearch":return await this.aemConnector.searchContent({fulltext:e.searchTerm,path:e.basePath,type:"cq:Page",limit:20});case"createPage":return await this.aemConnector.createPage(e);case"deletePage":return await this.aemConnector.deletePage(e);case"createComponent":return await this.aemConnector.createComponent(e);case"deleteComponent":return await this.aemConnector.deleteComponent(e);case"unpublishContent":return await this.aemConnector.unpublishContent(e);case"activatePage":return await this.aemConnector.activatePage(e);case"deactivatePage":return await this.aemConnector.deactivatePage(e);case"uploadAsset":return await this.aemConnector.uploadAsset(e);case"updateAsset":return await this.aemConnector.updateAsset(e);case"deleteAsset":return await this.aemConnector.deleteAsset(e);case"getTemplates":return await this.aemConnector.getTemplates(e.sitePath);case"getTemplateStructure":return await this.aemConnector.getTemplateStructure(e.templatePath);case"bulkUpdateComponents":return await this.aemConnector.bulkUpdateComponents(e);default:throw new Error(`Unknown method: ${t}`)}}catch(n){return{error:n.message,method:t,params:e}}}getWorkflowStatus(t){return{success:!0,workflowId:t,status:"completed",message:"Mock workflow status - always returns completed",timestamp:new Date().toISOString()}}async handleHealthCheck(){return{status:"healthy",aem:await this.aemConnector.testConnection()?"connected":"disconnected",mcp:"ready",timestamp:new Date().toISOString(),version:a.APP_VERSION||"1.0.0",port:this.config.mcpPort}}}
1
+ "use strict";import{AEMConnector as a}from"../aem/aem.connector.js";import{handleAEMHttpError as o}from"../aem/aem.errors.js";export class MCPRequestHandler{aemConnector;config;constructor(t){this.config=t,this.aemConnector=new a(t)}async init(){this.aemConnector.isInitialized?console.log("AEM Connector already initialized."):(await this.aemConnector.init(),console.log("AEM Connector initialized."))}async handleRequest(t,e){try{await this.init()}catch(n){throw console.error("ERROR initializing MCP Server",n.message),o(n,"MCP Server Initialization")}try{switch(t){case"validateComponent":return await this.aemConnector.validateComponent(e);case"updateComponent":return await this.aemConnector.updateComponent(e);case"undoChanges":return await this.aemConnector.undoChanges(e);case"scanPageComponents":return await this.aemConnector.scanPageComponents(e.pagePath);case"fetchSites":return await this.aemConnector.fetchSites();case"fetchLanguageMasters":return await this.aemConnector.fetchLanguageMasters(e.site);case"fetchAvailableLocales":return await this.aemConnector.fetchAvailableLocales(e.site,e.languageMasterPath);case"replicateAndPublish":return await this.aemConnector.replicateAndPublish(e.selectedLocales,e.componentData,e.localizedOverrides);case"getAllTextContent":return await this.aemConnector.getAllTextContent(e.pagePath);case"getPageTextContent":return await this.aemConnector.getPageTextContent(e.pagePath);case"getPageImages":return await this.aemConnector.getPageImages(e.pagePath);case"updateImagePath":return await this.aemConnector.updateImagePath(e.componentPath,e.newImagePath);case"getPageContent":return await this.aemConnector.getPageContent(e.pagePath);case"listPages":return await this.aemConnector.listPages(e.siteRoot||e.path||"/content",e.depth||1,e.limit||20);case"getNodeContent":return await this.aemConnector.getNodeContent(e.path,e.depth||1);case"listChildren":return await this.aemConnector.listChildren(e.path);case"getPageProperties":return await this.aemConnector.getPageProperties(e.pagePath);case"searchContent":return await this.aemConnector.searchContent(e);case"executeJCRQuery":return await this.aemConnector.executeJCRQuery(e.query,e.limit);case"getAssetMetadata":return await this.aemConnector.getAssetMetadata(e.assetPath);case"getStatus":return this.getWorkflowStatus(e.workflowId);case"enhancedPageSearch":return await this.aemConnector.searchContent({fulltext:e.searchTerm,path:e.basePath,type:"cq:Page",limit:20});case"createPage":return await this.aemConnector.createPage(e);case"deletePage":return await this.aemConnector.deletePage(e);case"createComponent":return await this.aemConnector.createComponent(e);case"deleteComponent":return await this.aemConnector.deleteComponent(e);case"unpublishContent":return await this.aemConnector.unpublishContent(e);case"activatePage":return await this.aemConnector.activatePage(e);case"deactivatePage":return await this.aemConnector.deactivatePage(e);case"uploadAsset":return await this.aemConnector.uploadAsset(e);case"updateAsset":return await this.aemConnector.updateAsset(e);case"deleteAsset":return await this.aemConnector.deleteAsset(e);case"getTemplates":case"getTemplateStructure":return await this.aemConnector.getTemplateStructure(e.templatePath);case"bulkUpdateComponents":return await this.aemConnector.bulkUpdateComponents(e);default:throw new Error(`Unknown method: ${t}`)}}catch(n){return{error:n.message,method:t,params:e}}}getWorkflowStatus(t){return{success:!0,workflowId:t,status:"completed",message:"Mock workflow status - always returns completed",timestamp:new Date().toISOString()}}}
@@ -1 +1 @@
1
- "use strict";import{randomUUID as p}from"node:crypto";import{StreamableHTTPServerTransport as m}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as u}from"@modelcontextprotocol/sdk/types.js";import{transports as t}from"./mcp.transports.js";import{createMCPServer as c}from"./mcp.server.js";export const handleRequest=async(e,o,a)=>{console.log("Received MCP request:",e.body),console.log("Route path:",e.route?.path),console.log("Full path:",e.baseUrl+e.path);const{jsonrpc:i,id:l,method:d,params:R}=e.body;if(i!=="2.0"||!d){o.status(400).json({jsonrpc:"2.0",id:l||null,error:{code:-32600,message:"Invalid Request",data:"Must be valid JSON-RPC 2.0"}});return}try{const s=e.headers["mcp-session-id"];let r;if(s&&t[s])r=t[s];else if(!s&&u(e.body)){r=new m({sessionIdGenerator:()=>p(),enableJsonResponse:!0,onsessioninitialized:n=>{console.log(`Session initialized with ID: ${n}`),t[n]=r}}),await c(a).connect(r),await r.handleRequest(e,o,e.body);return}else{o.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});return}await r.handleRequest(e,o,e.body)}catch(s){console.error("Error handling MCP request:",s),o.headersSent||o.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}};
1
+ "use strict";import{randomUUID as c}from"node:crypto";import{StreamableHTTPServerTransport as m}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as u}from"@modelcontextprotocol/sdk/types.js";import{transports as n}from"./mcp.transports.js";import{createMCPServer as p}from"./mcp.server.js";export const handleRequest=async(e,s,t)=>{console.log("1.Received MCP request:",e.body);const{jsonrpc:a,id:l,method:d,params:v}=e.body;if(a!=="2.0"||!d){s.status(400).json({jsonrpc:"2.0",id:l||null,error:{code:-32600,message:"Invalid Request",data:"Must be valid JSON-RPC 2.0"}});return}try{const o=e.headers["mcp-session-id"];let r;if(o&&n[o])console.log(`Session exists: ${o}`),r=n[o];else if(!o&&u(e.body)){r=new m({sessionIdGenerator:()=>c(),enableJsonResponse:!0,onsessioninitialized:i=>{console.log(`Session initialized with ID: ${i}`),n[i]=r}}),console.log("Connecting to MCP server with CLI params:",t),await p(t).connect(r),await r.handleRequest(e,s,e.body);return}else{console.log("Invalid request - no session ID or not initialization request"),s.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});return}await r.handleRequest(e,s,e.body)}catch(o){console.error("Error handling MCP request:",o),s.headersSent||s.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}};
@@ -1 +1 @@
1
- "use strict";import{CallToolRequestSchema as c,ListToolsRequestSchema as i}from"@modelcontextprotocol/sdk/types.js";import{Server as u}from"@modelcontextprotocol/sdk/server/index.js";import{tools as p}from"./mcp.tools.js";import{AEMConnector as l}from"../aem/aem.connector.js";import{MCPRequestHandler as f}from"./mcp.aem-handler.js";export const createMCPServer=t=>{const n=new l(t),s=new f(t,n),e=new u({name:"aem-mcp-server",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return e.setRequestHandler(i,async()=>({tools:p})),e.setRequestHandler(c,async a=>{const{name:m,arguments:o}=a.params;if(!o)return{content:[{type:"text",text:"Error: No arguments provided"}],isError:!0};try{const r=await s.handleRequest(m,o);return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(r){return{content:[{type:"text",text:`Error: ${r.message}`}],isError:!0}}}),e};
1
+ "use strict";import{CallToolRequestSchema as i,ListToolsRequestSchema as u}from"@modelcontextprotocol/sdk/types.js";import{Server as p}from"@modelcontextprotocol/sdk/server/index.js";import{tools as s}from"./mcp.tools.js";import{MCPRequestHandler as R}from"./mcp.aem-handler.js";export const createMCPServer=a=>{const n=new R(a),l={name:"aem-mcp-server",version:"1.0.0"},c={capabilities:{resources:{},tools:{}}},r=new p(l,c);return r.setRequestHandler(u,async()=>(console.log("2. Received ListToolsRequest",s),{tools:s})),r.setRequestHandler(i,async t=>{const{name:m,arguments:o}=t.params;if(console.log("Received CallToolRequestSchema",t.params),!o)return{content:[{type:"text",text:"Error: No arguments provided"}],isError:!0};try{const e=await n.handleRequest(m,o);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){return console.error("ERROR CallToolRequestSchema",e.message),{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),r};
@@ -1 +1 @@
1
- "use strict";import n from"express";import i from"cors";import{handleRequest as l}from"../mcp/mcp.server-handler.js";import{AEMConnector as p}from"../aem/aem.connector.js";import{MCPRequestHandler as d}from"../mcp/mcp.aem-handler.js";import{config as m}from"../config.js";const h=(o={})=>{const e=n();e.use(i({origin:"*",exposedHeaders:["Mcp-Session-Id"]})),e.use(n.json()),e.use(n.json({limit:"10mb"})),e.use(n.urlencoded({extended:!0}));const c=new p(o),r=new d(o,c);return e.get("/health",async(s,t)=>{try{const a=await r.handleHealthCheck();t.json(a)}catch(a){t.status(500).json({status:"unhealthy",error:a.message,timestamp:new Date().toISOString()})}}),e.post("/mcp",async(s,t)=>{console.log("Received MCP request:",s.body),await l(s,t,o)}),e.get("/mcp",async(s,t)=>{t.status(405).set("Allow","POST").send("Method Not Allowed")}),e.delete("/mcp",async(s,t)=>{console.log("Received DELETE MCP request"),t.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),e.get("/",(s,t)=>{t.json({name:"AEM MCP Gateway Server",description:"A Model Context Protocol server for Adobe Experience Manager",version:m.APP_VERSION||"1.0.0",endpoints:{health:{method:"GET",path:"/health",description:"Health check for all services"},mcp:{method:"POST",path:"/mcp",description:"JSON-RPC endpoint for MCP calls"},mcpMethods:{method:"GET",path:"/mcp/methods",description:"List all available MCP methods"}},architecture:"MCP integration",timestamp:new Date().toISOString()})}),e};export const startServer=(o={})=>{const{mcpPort:e=3e3}=o||{};h(o).listen(e,r=>{r&&(console.error("Failed to start server:",r),process.exit(1)),console.log(`AEM MCP Server listening on port ${e}`)})};process.on("SIGINT",async()=>{console.log("Shutting down server..."),process.exit(0)});
1
+ "use strict";import n from"express";import p from"cors";import{handleRequest as l}from"../mcp/mcp.server-handler.js";import{AEMConnector as m}from"../aem/aem.connector.js";import{config as c}from"../config.js";const d=(s={})=>{const e=n();e.use(p({origin:"*",exposedHeaders:["Mcp-Session-Id"]})),e.use(n.json()),e.use(n.json({limit:"10mb"})),e.use(n.urlencoded({extended:!0}));const r=new m(s);return e.get("/health",async(o,t)=>{try{await r.init();const i={status:"healthy",aem:await r.testConnection()?"connected":"disconnected",mcp:"ready",timestamp:new Date().toISOString(),version:c.APP_VERSION||"1.0.0"};t.json(i)}catch(a){t.status(500).json({status:"unhealthy",error:a.message,timestamp:new Date().toISOString()})}}),e.post("/mcp",async(o,t)=>{await l(o,t,s)}),e.get("/mcp",async(o,t)=>{t.status(405).set("Allow","POST").send("Method Not Allowed")}),e.delete("/mcp",async(o,t)=>{console.log("Received DELETE MCP request"),t.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),e.get("/",(o,t)=>{t.json({name:"AEM MCP Gateway Server",description:"A Model Context Protocol server for Adobe Experience Manager",version:c.APP_VERSION||"1.0.0",endpoints:{health:{method:"GET",path:"/health",description:"Health check for all services"},mcp:{method:"POST",path:"/mcp",description:"JSON-RPC endpoint for MCP calls"},mcpMethods:{method:"GET",path:"/mcp/methods",description:"List all available MCP methods"}},architecture:"MCP integration",timestamp:new Date().toISOString()})}),e};export const startServer=(s={})=>{const{mcpPort:e=3e3}=s||{};d(s).listen(e,o=>{o&&(console.error("Failed to start server:",o),process.exit(1)),console.log(`AEM MCP Server listening on port ${e}`)})};process.on("SIGINT",async()=>{console.log("Shutting down server..."),process.exit(0)});
package/docs/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ # [1.2.0](https://github.com/easingthemes/aem-mcp-server/compare/v1.1.5...v1.2.0) (2025-08-10)
2
+
3
+
4
+ ### Features
5
+
6
+ * add AEMaaCS OAuth support, add fetch retry on 401 ([0f53d1a](https://github.com/easingthemes/aem-mcp-server/commit/0f53d1a4bc8bc622f018f68c021d95e4a0791e78))
7
+
8
+ ## [1.1.5](https://github.com/easingthemes/aem-mcp-server/compare/v1.1.4...v1.1.5) (2025-08-08)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * remove invalid empty `prompts` ([92c64d3](https://github.com/easingthemes/aem-mcp-server/commit/92c64d3d2db3ff32ce0e2b651b22697940761dd0))
14
+
1
15
  ## [1.1.4](https://github.com/easingthemes/aem-mcp-server/compare/v1.1.3...v1.1.4) (2025-07-19)
2
16
 
3
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aem-mcp-server",
3
- "version": "1.1.4",
3
+ "version": "1.2.0",
4
4
  "description": "AEM Model Context Protocol (MCP) server",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -18,20 +18,22 @@
18
18
  "Adobe Experience Manager",
19
19
  "TypeScript"
20
20
  ],
21
- "main": "./dist/index.js",
21
+ "main": "dist/index.js",
22
+ "types": "dist/index.d.ts",
22
23
  "bin": {
23
24
  "aem-mcp": "dist/cli.js"
24
25
  },
25
26
  "files": [
26
- "cli/**/*.js",
27
27
  "dist/**/*.js",
28
+ "build/**/*.d.ts",
28
29
  "docs/",
29
30
  "README.md",
30
31
  "LICENSE"
31
32
  ],
32
33
  "scripts": {
33
- "build": "esbuild src/**/*.ts src/*.ts --outdir=dist --platform=node --minify",
34
- "build:cjs": "esbuild src/**/*.ts src/*.ts --outdir=dist --platform=node --format=cjs",
34
+ "build": "npm run build:types && npm run build:ts",
35
+ "build:ts": "esbuild src/**/*.ts src/*.ts --outdir=dist --platform=node --minify",
36
+ "build:types": "tsc --emitDeclarationOnly",
35
37
  "start": "node dist/index.js",
36
38
  "test:dev": "node ./dist/cli.js",
37
39
  "test:npm": "npm pack && npm install -g ./aem-mcp-server-$npm_package_version.tgz && aem-mcp -e -H=http://localhost:5502"
@@ -48,7 +50,8 @@
48
50
  "@types/express": "^5.0.3",
49
51
  "@types/node": "^24.0.14",
50
52
  "@types/yargs": "^17.0.33",
51
- "esbuild": "^0.25.6"
53
+ "esbuild": "^0.25.6",
54
+ "typescript": "^5.8.3"
52
55
  },
53
56
  "type": "module"
54
57
  }