-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathxero-client.ts
172 lines (143 loc) · 4.62 KB
/
xero-client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import axios, { AxiosError } from "axios";
import dotenv from "dotenv";
import {
IXeroClientConfig,
Organisation,
TokenSet,
XeroClient,
} from "xero-node";
import { ensureError } from "../helpers/ensure-error.js";
dotenv.config();
const client_id = process.env.XERO_CLIENT_ID;
const client_secret = process.env.XERO_CLIENT_SECRET;
const bearer_token = process.env.XERO_CLIENT_BEARER_TOKEN;
const grant_type = "client_credentials";
if (!bearer_token && (!client_id || !client_secret)) {
throw Error("Environment Variables not set - please check your .env file");
}
abstract class MCPXeroClient extends XeroClient {
public tenantId: string;
private shortCode: string;
protected constructor(config?: IXeroClientConfig) {
super(config);
this.tenantId = "";
this.shortCode = "";
}
public abstract authenticate(): Promise<void>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
override async updateTenants(fullOrgDetails?: boolean): Promise<any[]> {
await super.updateTenants(fullOrgDetails);
if (this.tenants && this.tenants.length > 0) {
this.tenantId = this.tenants[0].tenantId;
}
return this.tenants;
}
private async getOrganisation(): Promise<Organisation> {
await this.authenticate();
const organisationResponse = await this.accountingApi.getOrganisations(
this.tenantId || "",
);
const organisation = organisationResponse.body.organisations?.[0];
if (!organisation) {
throw new Error("Failed to retrieve organisation");
}
return organisation;
}
public async getShortCode(): Promise<string | undefined> {
if (!this.shortCode) {
try {
const organisation = await this.getOrganisation();
this.shortCode = organisation.shortCode ?? "";
} catch (error: unknown) {
const err = ensureError(error);
throw new Error(
`Failed to get Organisation short code: ${err.message}`,
);
}
}
return this.shortCode;
}
}
class CustomConnectionsXeroClient extends MCPXeroClient {
private readonly clientId: string;
private readonly clientSecret: string;
constructor(config: {
clientId: string;
clientSecret: string;
grantType: string;
}) {
super(config);
this.clientId = config.clientId;
this.clientSecret = config.clientSecret;
}
public async getClientCredentialsToken(): Promise<TokenSet> {
const scope =
"accounting.transactions accounting.contacts accounting.settings accounting.reports.read accounting.transactions payroll.settings payroll.employees payroll.timesheets";
const credentials = Buffer.from(
`${this.clientId}:${this.clientSecret}`,
).toString("base64");
try {
const response = await axios.post(
"https://identity.xero.com/connect/token",
`grant_type=client_credentials&scope=${encodeURIComponent(scope)}`,
{
headers: {
Authorization: `Basic ${credentials}`,
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
},
);
// Get the tenant ID from the connections endpoint
const token = response.data.access_token;
const connectionsResponse = await axios.get(
"https://api.xero.com/connections",
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
},
},
);
if (connectionsResponse.data && connectionsResponse.data.length > 0) {
this.tenantId = connectionsResponse.data[0].tenantId;
}
return response.data;
} catch (error) {
const axiosError = error as AxiosError;
throw new Error(
`Failed to get Xero token: ${axiosError.response?.data || axiosError.message}`,
);
}
}
public async authenticate() {
const tokenResponse = await this.getClientCredentialsToken();
this.setTokenSet({
access_token: tokenResponse.access_token,
expires_in: tokenResponse.expires_in,
token_type: tokenResponse.token_type,
});
}
}
class BearerTokenXeroClient extends MCPXeroClient {
private readonly bearerToken: string;
constructor(config: { bearerToken: string }) {
super();
this.bearerToken = config.bearerToken;
}
async authenticate(): Promise<void> {
this.setTokenSet({
access_token: this.bearerToken,
});
await this.updateTenants();
}
}
export const xeroClient = bearer_token
? new BearerTokenXeroClient({
bearerToken: bearer_token,
})
: new CustomConnectionsXeroClient({
clientId: client_id!,
clientSecret: client_secret!,
grantType: grant_type,
});