or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcore-ai.mdide-integration.mdindex.mdmcp-oauth.mdservices.mdtelemetry.mdtools.mdutilities.md

mcp-oauth.mddocs/

0

# MCP and OAuth

1

2

Model Context Protocol (MCP) integration with OAuth authentication for secure server connections and token management.

3

4

## Capabilities

5

6

### MCPOAuthProvider

7

8

OAuth provider for authenticating with MCP servers using OAuth 2.0 flows.

9

10

```typescript { .api }

11

/**

12

* OAuth provider for MCP server authentication

13

*/

14

class MCPOAuthProvider {

15

constructor(tokenStorage?: MCPOAuthTokenStorage);

16

17

/**

18

* Perform OAuth authentication flow

19

* @param serverName - Name of the MCP server

20

* @param config - OAuth configuration

21

* @param mcpServerUrl - Optional MCP server URL

22

* @returns OAuth token

23

*/

24

authenticate(

25

serverName: string,

26

config: MCPOAuthConfig,

27

mcpServerUrl?: string

28

): Promise<OAuthToken>;

29

30

/**

31

* Get a valid token, refreshing if necessary

32

* @param serverName - Name of the MCP server

33

* @param config - OAuth configuration

34

* @returns Valid access token or null if authentication required

35

*/

36

getValidToken(serverName: string, config: MCPOAuthConfig): Promise<string | null>;

37

38

/**

39

* Refresh an access token using refresh token

40

* @param serverName - Name of the MCP server

41

* @param config - OAuth configuration

42

* @param refreshToken - Refresh token

43

* @returns New OAuth token

44

*/

45

refreshAccessToken(

46

serverName: string,

47

config: MCPOAuthConfig,

48

refreshToken: string

49

): Promise<OAuthToken>;

50

51

/**

52

* Revoke tokens for a server

53

* @param serverName - Name of the MCP server

54

* @param config - OAuth configuration

55

*/

56

revokeTokens(serverName: string, config: MCPOAuthConfig): Promise<void>;

57

58

/**

59

* Check if authentication is required

60

* @param serverName - Name of the MCP server

61

* @returns True if authentication is required

62

*/

63

isAuthenticationRequired(serverName: string): Promise<boolean>;

64

}

65

```

66

67

### OAuth Configuration

68

69

Configuration interfaces and types for OAuth authentication setup.

70

71

```typescript { .api }

72

/**

73

* OAuth configuration for MCP servers

74

*/

75

interface MCPOAuthConfig {

76

/** OAuth authorization endpoint URL */

77

authorizationUrl: string;

78

/** OAuth token endpoint URL */

79

tokenUrl: string;

80

/** OAuth client identifier */

81

clientId: string;

82

/** OAuth client secret (optional for public clients) */

83

clientSecret?: string;

84

/** OAuth scopes to request */

85

scopes?: string[];

86

/** OAuth redirect URI */

87

redirectUri?: string;

88

/** Additional OAuth parameters */

89

additionalParams?: Record<string, string>;

90

/** PKCE support */

91

usePKCE?: boolean;

92

}

93

94

/**

95

* OAuth authorization response

96

*/

97

interface OAuthAuthorizationResponse {

98

/** Authorization code */

99

code: string;

100

/** State parameter for CSRF protection */

101

state?: string;

102

/** Error code if authorization failed */

103

error?: string;

104

/** Error description */

105

errorDescription?: string;

106

}

107

108

/**

109

* OAuth token response

110

*/

111

interface OAuthTokenResponse {

112

/** Access token */

113

accessToken: string;

114

/** Token type (usually 'Bearer') */

115

tokenType: string;

116

/** Token expiration time in seconds */

117

expiresIn?: number;

118

/** Refresh token */

119

refreshToken?: string;

120

/** Token scope */

121

scope?: string;

122

}

123

124

/**

125

* OAuth client registration request

126

*/

127

interface OAuthClientRegistrationRequest {

128

/** Client name */

129

clientName: string;

130

/** Redirect URIs */

131

redirectUris: string[];

132

/** Grant types */

133

grantTypes: string[];

134

/** Response types */

135

responseTypes: string[];

136

/** Token endpoint auth method */

137

tokenEndpointAuthMethod?: string;

138

/** Application type */

139

applicationType?: 'web' | 'native';

140

}

141

142

/**

143

* OAuth client registration response

144

*/

145

interface OAuthClientRegistrationResponse {

146

/** Client identifier */

147

clientId: string;

148

/** Client secret */

149

clientSecret?: string;

150

/** Client ID issued at timestamp */

151

clientIdIssuedAt?: number;

152

/** Client secret expiration */

153

clientSecretExpiresAt?: number;

154

/** Registration access token */

155

registrationAccessToken?: string;

156

/** Registration client URI */

157

registrationClientUri?: string;

158

}

159

```

160

161

### OAuth Token Storage

162

163

Secure token storage and management for OAuth credentials.

164

165

```typescript { .api }

166

/**

167

* OAuth token storage management

168

*/

169

class MCPOAuthTokenStorage {

170

constructor(storagePath?: string);

171

172

/**

173

* Store OAuth token for a server

174

* @param serverName - Name of the MCP server

175

* @param token - OAuth token to store

176

*/

177

storeToken(serverName: string, token: OAuthToken): Promise<void>;

178

179

/**

180

* Retrieve OAuth token for a server

181

* @param serverName - Name of the MCP server

182

* @returns Stored OAuth token or null if not found

183

*/

184

getToken(serverName: string): Promise<OAuthToken | null>;

185

186

/**

187

* Delete OAuth token for a server

188

* @param serverName - Name of the MCP server

189

*/

190

deleteToken(serverName: string): Promise<void>;

191

192

/**

193

* List all stored server names

194

* @returns Array of server names with stored tokens

195

*/

196

listServers(): Promise<string[]>;

197

198

/**

199

* Clear all stored tokens

200

*/

201

clearAllTokens(): Promise<void>;

202

203

/**

204

* Check if token exists for server

205

* @param serverName - Name of the MCP server

206

* @returns True if token exists

207

*/

208

hasToken(serverName: string): Promise<boolean>;

209

}

210

```

211

212

### Token Types

213

214

Type definitions for OAuth tokens and credentials.

215

216

```typescript { .api }

217

/**

218

* OAuth token structure

219

*/

220

interface OAuthToken {

221

/** Access token */

222

accessToken: string;

223

/** Token type */

224

tokenType: string;

225

/** Token expiration timestamp (Unix timestamp) */

226

expiresAt?: number;

227

/** Refresh token */

228

refreshToken?: string;

229

/** Token scope */

230

scope?: string;

231

/** Additional token metadata */

232

metadata?: Record<string, any>;

233

}

234

235

/**

236

* OAuth credentials structure

237

*/

238

interface OAuthCredentials {

239

/** Client identifier */

240

clientId: string;

241

/** Client secret */

242

clientSecret?: string;

243

/** Authorization server metadata */

244

authorizationServerMetadata?: OAuthAuthorizationServerMetadata;

245

/** Protected resource metadata */

246

protectedResourceMetadata?: OAuthProtectedResourceMetadata;

247

}

248

```

249

250

### OAuth Utilities

251

252

Utility functions and classes for OAuth operations and metadata handling.

253

254

```typescript { .api }

255

/**

256

* OAuth utility functions and helpers

257

*/

258

class OAuthUtils {

259

/**

260

* Generate PKCE code verifier and challenge

261

* @returns PKCE parameters

262

*/

263

static generatePKCE(): {

264

codeVerifier: string;

265

codeChallenge: string;

266

codeChallengeMethod: string;

267

};

268

269

/**

270

* Build authorization URL with parameters

271

* @param config - OAuth configuration

272

* @param state - State parameter

273

* @param codeChallenge - PKCE code challenge

274

* @returns Authorization URL

275

*/

276

static buildAuthorizationUrl(

277

config: MCPOAuthConfig,

278

state?: string,

279

codeChallenge?: string

280

): string;

281

282

/**

283

* Parse authorization response from URL

284

* @param url - Authorization response URL

285

* @returns Parsed authorization response

286

*/

287

static parseAuthorizationResponse(url: string): OAuthAuthorizationResponse;

288

289

/**

290

* Exchange authorization code for tokens

291

* @param config - OAuth configuration

292

* @param authorizationCode - Authorization code

293

* @param codeVerifier - PKCE code verifier

294

* @returns OAuth token response

295

*/

296

static exchangeCodeForTokens(

297

config: MCPOAuthConfig,

298

authorizationCode: string,

299

codeVerifier?: string

300

): Promise<OAuthTokenResponse>;

301

302

/**

303

* Validate token expiration

304

* @param token - OAuth token to validate

305

* @param bufferSeconds - Buffer time before expiration

306

* @returns True if token is valid

307

*/

308

static isTokenValid(token: OAuthToken, bufferSeconds?: number): boolean;

309

310

/**

311

* Discover OAuth server metadata

312

* @param issuerUrl - OAuth issuer URL

313

* @returns Authorization server metadata

314

*/

315

static discoverServerMetadata(issuerUrl: string): Promise<OAuthAuthorizationServerMetadata>;

316

}

317

318

/**

319

* OAuth authorization server metadata

320

*/

321

interface OAuthAuthorizationServerMetadata {

322

/** Issuer identifier */

323

issuer: string;

324

/** Authorization endpoint */

325

authorizationEndpoint: string;

326

/** Token endpoint */

327

tokenEndpoint: string;

328

/** Supported response types */

329

responseTypesSupported: string[];

330

/** Supported subject types */

331

subjectTypesSupported: string[];

332

/** Supported ID token signing algorithms */

333

idTokenSigningAlgValuesSupported: string[];

334

/** Revocation endpoint */

335

revocationEndpoint?: string;

336

/** Introspection endpoint */

337

introspectionEndpoint?: string;

338

/** JWKS URI */

339

jwksUri?: string;

340

/** Supported scopes */

341

scopesSupported?: string[];

342

/** Supported grant types */

343

grantTypesSupported?: string[];

344

/** Supported token endpoint auth methods */

345

tokenEndpointAuthMethodsSupported?: string[];

346

/** PKCE support */

347

codeChallengeMethodsSupported?: string[];

348

}

349

350

/**

351

* OAuth protected resource metadata

352

*/

353

interface OAuthProtectedResourceMetadata {

354

/** Resource identifier */

355

resource: string;

356

/** Authorization servers */

357

authorizationServers?: string[];

358

/** Bearer token usage */

359

bearerTokenUsage?: string[];

360

/** Resource documentation */

361

resourceDocumentation?: string;

362

}

363

```

364

365

### MCP Prompt Integration

366

367

Prompt templates and utilities for MCP server interactions.

368

369

```typescript { .api }

370

/**

371

* MCP-specific prompt logic and templates

372

*/

373

namespace MCPPrompts {

374

/**

375

* Generate authentication prompt for MCP server

376

* @param serverName - Name of the MCP server

377

* @param config - OAuth configuration

378

* @returns Authentication prompt

379

*/

380

function getAuthenticationPrompt(serverName: string, config: MCPOAuthConfig): string;

381

382

/**

383

* Generate server connection prompt

384

* @param serverName - Name of the MCP server

385

* @returns Connection prompt

386

*/

387

function getConnectionPrompt(serverName: string): string;

388

389

/**

390

* Generate tool invocation prompt

391

* @param serverName - Name of the MCP server

392

* @param toolName - Name of the tool

393

* @param parameters - Tool parameters

394

* @returns Tool invocation prompt

395

*/

396

function getToolInvocationPrompt(

397

serverName: string,

398

toolName: string,

399

parameters: any

400

): string;

401

}

402

```

403

404

**Usage Examples:**

405

406

```typescript

407

import {

408

MCPOAuthProvider,

409

MCPOAuthTokenStorage,

410

OAuthUtils,

411

MCPOAuthConfig,

412

OAuthToken

413

} from '@google/gemini-cli-core';

414

415

// Setup OAuth provider with token storage

416

const tokenStorage = new MCPOAuthTokenStorage();

417

const oauthProvider = new MCPOAuthProvider(tokenStorage);

418

419

// Configure OAuth for an MCP server

420

const mcpConfig: MCPOAuthConfig = {

421

authorizationUrl: 'https://auth.example.com/oauth/authorize',

422

tokenUrl: 'https://auth.example.com/oauth/token',

423

clientId: 'mcp-client-123',

424

scopes: ['read', 'write'],

425

usePKCE: true

426

};

427

428

// Check if authentication is required

429

const serverName = 'example-mcp-server';

430

const authRequired = await oauthProvider.isAuthenticationRequired(serverName);

431

432

if (authRequired) {

433

console.log('Authentication required, starting OAuth flow...');

434

435

// Perform authentication

436

const token = await oauthProvider.authenticate(serverName, mcpConfig);

437

console.log('Authentication successful!');

438

console.log(`Token expires at: ${new Date(token.expiresAt! * 1000)}`);

439

} else {

440

console.log('Using existing authentication');

441

}

442

443

// Get a valid token (will refresh if needed)

444

const validToken = await oauthProvider.getValidToken(serverName, mcpConfig);

445

446

if (validToken) {

447

console.log('Got valid token:', validToken.substring(0, 10) + '...');

448

449

// Use the token for MCP server requests

450

// ... MCP client code here ...

451

} else {

452

console.log('Failed to obtain valid token');

453

}

454

455

// OAuth utilities usage

456

const pkceParams = OAuthUtils.generatePKCE();

457

console.log('Generated PKCE verifier:', pkceParams.codeVerifier);

458

459

const authUrl = OAuthUtils.buildAuthorizationUrl(mcpConfig, 'random-state', pkceParams.codeChallenge);

460

console.log('Authorization URL:', authUrl);

461

462

// Token validation

463

const storedToken = await tokenStorage.getToken(serverName);

464

if (storedToken && OAuthUtils.isTokenValid(storedToken, 300)) { // 5 minute buffer

465

console.log('Stored token is still valid');

466

} else {

467

console.log('Stored token expired or invalid');

468

}

469

470

// Server metadata discovery

471

try {

472

const metadata = await OAuthUtils.discoverServerMetadata('https://auth.example.com');

473

console.log('Discovered server metadata:', metadata.issuer);

474

console.log('Supported scopes:', metadata.scopesSupported);

475

} catch (error) {

476

console.error('Failed to discover server metadata:', error);

477

}

478

479

// Token storage management

480

const allServers = await tokenStorage.listServers();

481

console.log('Servers with stored tokens:', allServers);

482

483

// Clear expired or unwanted tokens

484

for (const server of allServers) {

485

const token = await tokenStorage.getToken(server);

486

if (token && !OAuthUtils.isTokenValid(token)) {

487

await tokenStorage.deleteToken(server);

488

console.log(`Deleted expired token for ${server}`);

489

}

490

}

491

```