Skip to content

Commit 85a5324

Browse files
patch: Define user-agent for API Calls towards Dynatrace (#50)
1 parent b540a6e commit 85a5324

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

src/dynatrace-clients.ts

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import { _OAuthHttpClient } from '@dynatrace-sdk/http-client';
1+
import { _OAuthHttpClient, HttpClientRequestOptions, HttpClientResponse, RequestBodyTypes } from '@dynatrace-sdk/http-client';
22
import { getSSOUrl } from 'dt-app';
3+
import { version as VERSION } from '../package.json';
34

4-
5-
// {"errorCode":400,"message":"Bad Request","issueId":"<some-id>","error":"invalid_request","error_description":""}
6-
5+
// Define the OAuthTokenResponse interface to match the expected structure of the response
76
export interface OAuthTokenResponse {
87
scope?: string;
98
token_type?: string;
@@ -46,6 +45,32 @@ const requestToken = async (clientId: string, clientSecret: string, authUrl: str
4645
return await res.json();
4746
}
4847

48+
/**
49+
* ExtendedOAuthClient that takes parameters for clientId, secret, scopes, environmentUrl, authUrl, and the version of the dynatrace-mcp-server
50+
*/
51+
export class ExtendedOauthClient extends _OAuthHttpClient {
52+
constructor(config: {
53+
clientId: string;
54+
secret: string;
55+
scopes: string[];
56+
environmentUrl: string;
57+
authUrl: string;
58+
}, protected userAgent: string) {
59+
super(config);
60+
}
61+
62+
send<T extends keyof RequestBodyTypes = 'json'>(options: HttpClientRequestOptions<T>): Promise<HttpClientResponse> {
63+
// add the user-agent header to the request
64+
options.headers = {
65+
...options.headers,
66+
'User-Agent': this.userAgent,
67+
};
68+
// call the parent send method
69+
return super.send(options);
70+
}
71+
}
72+
73+
4974
/** Create an Oauth Client based on clientId, clientSecret, environmentUrl and scopes */
5075
export const createOAuthClient = async (clientId: string, clientSecret: string, environmentUrl: string, scopes: string[]): Promise<_OAuthHttpClient> => {
5176
if (!clientId) {
@@ -73,13 +98,15 @@ export const createOAuthClient = async (clientId: string, clientSecret: string,
7398
}
7499
console.error(`Successfully retrieved token from SSO!`);
75100

76-
return new _OAuthHttpClient({
101+
const userAgent = `dynatrace-mcp-server/v${VERSION} (${process.platform}-${process.arch})`
102+
103+
return new ExtendedOauthClient({
77104
scopes,
78105
clientId,
79106
secret: clientSecret,
80107
environmentUrl,
81108
authUrl: ssoAuthUrl,
82-
});
109+
}, userAgent);
83110
};
84111

85112
/** Helper function to call an app-function via platform-api */

0 commit comments

Comments
 (0)