Skip to content

aspiers/ai-config / .agents/skills/xero-mcp

xero-mcp

Verified

Use the Xero MCP server — troubleshoot its self-refreshing OAuth2 token file, maintain the local best-of-breed server build, and pick up other operational notes for working with Xero MCP tools. Use when Xero MCP tools fail with authentication errors, before starting any Xero workflow, when adding or updating upstream xero-mcp-server PRs, or for general guidance on Xero MCP usage.

FileKindSize
SKILL.mdskill md4.7 KB
references/authentication.mdmarkdown6.4 KB
references/local-server.mdmarkdown5.3 KB
references/manual-journals.mdmarkdown3.8 KB
references/mcp-vs-browser.mdmarkdown3.8 KB
references/searching-records.mdmarkdown4.2 KB
scripts/xero-oauthexecutablescript11.3 KB

scripts/xero-oauth

View on GitHub
#!/usr/bin/env -S node --env-file=.env
// Xero OAuth2 flow helper
//
// Reads XERO_CLIENT_ID, XERO_CLIENT_SECRET and XERO_TOKEN_FILE from .env
// (via --env-file). Must be run from the repo root.
//
// Writes the OAuth2 token store at XERO_TOKEN_FILE, which the Xero MCP
// server (XERO_TOKEN_FILE auth mode) reads on every tool call and keeps
// refreshed itself, so no restart is needed after running this.
//
// Usage:
//   ./xero-oauth           # full OAuth flow, read-only scopes (browser required)
//   ./xero-oauth --write   # full OAuth flow, read+write scopes
//   ./xero-oauth --refresh # rotate the stored refresh token now

import http from 'http';
import https from 'https';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { spawn } from 'child_process';
import { URL } from 'url';

const TOKEN_FILE = process.env.XERO_TOKEN_FILE;

// Must match the MCP server's token-store lock protocol: an O_EXCL
// `<token file>.lock`, treated as stale after 60s. Xero rotates the refresh
// token on every use, so refreshing concurrently with the server could leave
// a spent refresh token on disk.
const LOCK_STALE_MS = 60_000;
const LOCK_TIMEOUT_MS = 45_000;

const REDIRECT_URI = 'http://localhost:8080/callback';

// Scopes reference: https://developer.xero.com/documentation/guides/oauth2/scopes/
// OpenAPI spec (uses deprecated broad scopes): https://github.com/XeroAPI/Xero-OpenAPI/blob/master/xero_accounting.yaml
const BASE_SCOPES = ['openid', 'offline_access'];

const ACCOUNTING_SCOPES_RO = [
  'accounting.contacts.read',
  'accounting.settings.read',
  'accounting.invoices.read',
  'accounting.payments.read',
  'accounting.banktransactions.read',
  'accounting.manualjournals.read',
  'accounting.reports.aged.read',
  'accounting.reports.balancesheet.read',
  'accounting.reports.profitandloss.read',
  'accounting.reports.trialbalance.read',
];

const ACCOUNTING_SCOPES_RW = [
  'accounting.contacts',
  'accounting.settings',
  'accounting.invoices',
  'accounting.payments',
  'accounting.banktransactions',
  'accounting.manualjournals',
  'accounting.reports.aged.read',
  'accounting.reports.balancesheet.read',
  'accounting.reports.profitandloss.read',
  'accounting.reports.trialbalance.read',
];

// Exchange tokens with Xero identity server
function fetchTokens(credentials, body) {
  return new Promise((resolve, reject) => {
    const req = https.request({
      hostname: 'identity.xero.com',
      path: '/connect/token',
      method: 'POST',
      headers: {
        'Authorization': `Basic ${credentials}`,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(body),
      },
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({ status: res.statusCode, body: data }));
    });
    req.on('error', reject);
    req.write(body);
    req.end();
  });
}

async function withTokenLock(fn) {
  const lock = `${TOKEN_FILE}.lock`;
  const deadline = Date.now() + LOCK_TIMEOUT_MS;
  fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true, mode: 0o700 });
  for (;;) {
    try {
      fs.closeSync(fs.openSync(lock, 'wx', 0o600));
      break;
    } catch (error) {
      if (error.code !== 'EEXIST') throw error;
    }
    try {
      if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) {
        fs.rmSync(lock, { force: true });
        continue;
      }
    } catch {
      continue;
    }
    if (Date.now() > deadline) throw new Error(`Timed out waiting for ${lock}`);
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  try {
    return await fn();
  } finally {
    fs.rmSync(lock, { force: true });
  }
}

function readTokenFile() {
  try {
    return JSON.parse(fs.readFileSync(TOKEN_FILE, 'utf8'));
  } catch (error) {
    if (error.code === 'ENOENT') return null;
    throw new Error(`${TOKEN_FILE} is unreadable or not valid JSON`);
  }
}

// Same shape and atomic 0600 write as the MCP server's persistTokens().
function writeTokenFile(tokens) {
  if (!tokens.access_token || !tokens.refresh_token) {
    throw new Error('Xero returned no access or refresh token');
  }
  const now = Math.floor(Date.now() / 1000);
  tokens._obtained_at = now;
  tokens.expires_at = now + (tokens.expires_in ?? 1800);

  const tmp = `${TOKEN_FILE}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
  const fd = fs.openSync(tmp, 'wx', 0o600);
  try {
    fs.writeSync(fd, JSON.stringify(tokens, null, 2));
    fs.fsyncSync(fd);
  } finally {
    fs.closeSync(fd);
  }
  fs.renameSync(tmp, TOKEN_FILE);
  const dirFd = fs.openSync(path.dirname(TOKEN_FILE), 'r');
  try {
    fs.fsyncSync(dirFd);
  } finally {
    fs.closeSync(dirFd);
  }
  console.log(`${TOKEN_FILE} updated; access token valid for ${tokens.expires_in ?? 1800}s.`);
  console.log('The Xero MCP server reads this file on every call and refreshes it');
  console.log('itself, so no restart is needed.');
}

// So XERO_TENANT_ID can be pinned: unpinned, the server writes to whichever
// connected organisation Xero happens to list first.
function printConnections(accessToken) {
  return new Promise((resolve) => {
    https.get('https://api.xero.com/connections', {
      headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const connections = JSON.parse(data);
          console.log('\nConnected organisations (set XERO_TENANT_ID in .env to one of these):');
          for (const c of connections) console.log(`  ${c.tenantId}  ${c.tenantName}`);
          if (!process.env.XERO_TENANT_ID) console.log('WARNING: XERO_TENANT_ID is not set.');
        } catch {
          console.error(`Could not list connections (HTTP ${res.statusCode}).`);
        }
        resolve();
      });
    }).on('error', (error) => {
      console.error(`Could not list connections: ${error.message}`);
      resolve();
    });
  });
}

async function refresh(credentials) {
  const tokens = await withTokenLock(async () => {
    // XERO_REFRESH_TOKEN in .env only seeds a token file that doesn't exist
    // yet; afterwards the file is the sole source, as the server rotates it.
    const refreshToken = readTokenFile()?.refresh_token ?? process.env.XERO_REFRESH_TOKEN;
    if (!refreshToken) {
      throw new Error(`No refresh token in ${TOKEN_FILE} or .env. Run without --refresh first.`);
    }

    console.log('Refreshing access token...');
    const body = new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
    }).toString();

    const tokenRes = await fetchTokens(credentials, body);
    const fresh = JSON.parse(tokenRes.body);
    if (!fresh.access_token) {
      throw new Error(`Error refreshing token (HTTP ${tokenRes.status}): ${fresh.error ?? 'unknown error'}`);
    }
    writeTokenFile(fresh);
    return fresh;
  });
  await printConnections(tokens.access_token);
}

async function fullOAuthFlow(credentials, scopes) {
  const authUrl = new URL('https://login.xero.com/identity/connect/authorize');
  authUrl.searchParams.set('response_type', 'code');
  authUrl.searchParams.set('client_id', process.env.XERO_CLIENT_ID);
  authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
  authUrl.searchParams.set('scope', scopes);
  authUrl.searchParams.set('state', 'xero-mcp');

  const url = authUrl.toString();
  console.log('\n=== Xero OAuth Flow ===\n');
  console.log('Make sure http://localhost:8080/callback is added as a redirect URI in your Xero app.\n');
  console.log('Opening browser...');
  console.log(url);
  spawn('open', [url], { detached: true, stdio: 'ignore' }).unref();
  console.log('\nWaiting for callback on port 8080...\n');

  const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, 'http://localhost:8080');
    if (url.pathname !== '/callback') {
      res.end('Not found');
      return;
    }

    const code = url.searchParams.get('code');
    if (!code) {
      res.end('Error: no code in callback');
      return;
    }

    const body = new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: REDIRECT_URI,
    }).toString();

    const tokenRes = await fetchTokens(credentials, body);
    const tokens = JSON.parse(tokenRes.body);

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Success! Check your terminal.');

    server.close();
    console.log('');
    await withTokenLock(async () => writeTokenFile(tokens));
    await printConnections(tokens.access_token);
  });

  server.listen(8080);
}

function printUsage() {
  process.stdout.write(`xero-oauth — obtain or rotate the Xero MCP server's OAuth2 token file

Usage:
  xero-oauth              Run the full OAuth flow with read-only scopes (browser required).
  xero-oauth --write      Run the full OAuth flow with read+write scopes.
  xero-oauth --refresh    Rotate the stored refresh token now.
  xero-oauth -h, --help   Show this help and exit.

Reads:
  .env                    XERO_CLIENT_ID, XERO_CLIENT_SECRET, XERO_TOKEN_FILE,
                          and optionally XERO_TENANT_ID. XERO_REFRESH_TOKEN
                          is only used to seed a token file that doesn't exist.

Writes:
  $XERO_TOKEN_FILE        The token store (0600), under the same lock the
                          MCP server uses when it refreshes the file.

The MCP server (XERO_TOKEN_FILE auth mode) reads the token file on every tool
call and refreshes it itself, so there is no need to restart the agent session
after running this. --refresh is only needed if the server has been idle for
long enough that the refresh token is about to expire (60 days unused).
`);
}

async function main() {
  if (process.argv.includes('-h') || process.argv.includes('--help')) {
    printUsage();
    return;
  }

  const clientId = process.env.XERO_CLIENT_ID;
  const clientSecret = process.env.XERO_CLIENT_SECRET;

  if (!clientId || !clientSecret || !TOKEN_FILE) {
    console.error('Error: XERO_CLIENT_ID, XERO_CLIENT_SECRET and XERO_TOKEN_FILE must be set in .env');
    process.exit(1);
  }

  const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');

  const writeMode = process.argv.includes('--write');
  const refreshMode = process.argv.includes('--refresh');

  const knownFlags = new Set(['--write', '--refresh', '-h', '--help']);
  const unknown = process.argv.slice(2).filter(a => !knownFlags.has(a));
  if (unknown.length > 0) {
    console.error(`Error: unknown argument(s): ${unknown.join(' ')}`);
    console.error('Run with --help for usage.');
    process.exit(2);
  }

  if (writeMode && refreshMode) {
    console.error('Error: --write and --refresh cannot be combined.');
    console.error('--refresh reuses the scopes from the original authorization.');
    console.error('To switch scopes, run a full OAuth flow: ./xero-oauth --write');
    process.exit(1);
  }

  if (refreshMode) {
    try {
      await refresh(credentials);
    } catch (error) {
      console.error(`Error: ${error.message}`);
      process.exit(1);
    }
  } else {
    const accountingScopes = writeMode ? ACCOUNTING_SCOPES_RW : ACCOUNTING_SCOPES_RO;
    const scopes = [...BASE_SCOPES, ...accountingScopes].join(' ');

    if (writeMode) {
      console.log('Using read+write scopes.');
    } else {
      console.log('Using read-only scopes (pass --write for read+write).');
    }

    await fullOAuthFlow(credentials, scopes);
  }
}

main();
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall