diff --git a/src/index.ts b/src/index.ts index 5451c1f..fef8f3e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,7 +24,7 @@ server.registerTool( content: [ { type: 'text', text: "TIP: Before executing any of the command run the 'm365_get_command_docs' tool to retrieve more context about it" }, { type: 'text', text: "TIP: avoid setting the '--output' option when running commands. The optimal output format is automatically selected in 'm365_run_command' tool based on the command type." }, - { type: 'text', text: JSON.stringify(commands, null, 2) } + { type: 'text', text: JSON.stringify(commands) } ] }; } diff --git a/src/util.ts b/src/util.ts index 41deb1c..e7c1df6 100644 --- a/src/util.ts +++ b/src/util.ts @@ -4,9 +4,18 @@ import { promises as fs } from 'fs'; export async function runCliCommand(command: string): Promise { - if (!command.includes('--output')) { + let isJsonOutput = false; + // Check if --output flag is already present (using precise pattern to avoid matching --output-file etc.) + if (!/--output(?:\s|=|$)/.test(command)) { const commandPart = command.split('--')[0].trim(); - command += commandPart.endsWith(' list') ? ' --output csv' : ' --output json'; + if (commandPart.endsWith(' list')) { + command += ' --output csv'; + } else { + command += ' --output json'; + isJsonOutput = true; + } + } else if (/--output[=\s]+json\b/.test(command)) { + isJsonOutput = true; } return new Promise((resolve, reject) => { @@ -28,7 +37,13 @@ export async function runCliCommand(command: string): Promise { subprocess.on('close', (code) => { if (code === 0) { - resolve(output.trim()); + const trimmedOutput = output.trim(); + // Compact JSON output to reduce token usage + if (isJsonOutput) { + resolve(compactJson(trimmedOutput)); + } else { + resolve(trimmedOutput); + } } else { reject(new Error(error.trim() || `Command failed with exit code ${code}`)); } @@ -123,4 +138,15 @@ async function checkGlobalPackage(packageName: string, filePath: string): Promis } }); }); +} + +function compactJson(output: string): string { + try { + // Try to parse and re-stringify the output to compact it + const parsed = JSON.parse(output); + return JSON.stringify(parsed); + } catch { + // If it's not valid JSON, return as-is + return output; + } } \ No newline at end of file