Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
]
};
}
Expand Down
32 changes: 29 additions & 3 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,18 @@ import { promises as fs } from 'fs';


export async function runCliCommand(command: string): Promise<string> {
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) => {
Expand All @@ -28,7 +37,13 @@ export async function runCliCommand(command: string): Promise<string> {

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}`));
}
Expand Down Expand Up @@ -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;
}
}