Hi everyone,
I’m trying to integrate NetSuite MCP Server with my custom AI Agent, but I keep running into authentication issues. Here’s what I’ve tried so far:
- OAuth 2.0 Setup
- Created an OAuth 2.0 credential in NetSuite.
- From the terminal, I successfully requested an access token.
- However, when I used that access token in a request with
Bearer <token>, I always received a 401 Unauthorized response.
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}",
"Content-Type": "application/json"
}
response = requests.post(
f"https://{ACCOUNT_ID}.app.netsuite.com/services/mcp/v1/all",
headers=headers,
json={
"jsonrpc": "2.0",
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {}
},
"id": 1
}
)
print(f"Status Code: {response.status_code}")
if response.status_code == 200:
print(f"SUCCESS! Response: {response.json()}")
else:
print(f"Response Text: {response.text}")
- I also tested other MCP endpoints, but all of them gave the same 401 response.
- Then I followed the same workflow that Claude uses to connect with NetSuite MCP.
First I'm gonna explain how is claude working:
Claude Integration
I followed the same workflow that Claude uses to connect with NetSuite MCP. With Claude (Anthropic’s AI), the process goes like this:
- I go into Claude’s settings → Connectors → Add Custom Connector.
- Then I enter the NetSuite AI Connector Service URL (something like
https://<account-id>.app.netsuite.com/services/mcp/v1/all) and give the connector a name. - I click Connect, which triggers a redirect to NetSuite’s OAuth 2.0 authentication screen.
- On that login/Auth screen, I select my custom MCP-enabled role (which is not the Administrator role), grant/allow the permissions, and confirm the connection.
- After authorization, NetSuite creates an integration record automatically under Setup → Integrations → Manage Integrations.
- Finally, in Claude I can see the new connector under Connectors, and in chat I can invoke NetSuite tools exposed via MCP (custom tools or those from the (“MCP Tools SuiteApp”) depending on what’s installed and what permissions the role has.
Because all of that works smoothly with Claude, I tried to replicate every step exactly in my AI Agent.
Issue with My AI Agent
- I followed the same OAuth flow in my own agent.
- I did reach the NetSuite login/authentication screen.
- But instead of successfully authenticating (as it does with Claude), entering credentials led straight to an “invalid login attempt” error.
- This happened even though my credentials, redirect URI, and scopes were correctly set.
- Because of this, I wasn’t able to obtain tokens or make MCP API calls.
This is my code setup Mimicking Claude
import os
import json
import time
import threading
import webbrowser
from urllib.parse import urlencode, urlparse
from queue import Queue, Empty
import secrets, string
import requests
from flask import Flask, request, Response
CLIENT_ID = "**************"
CLIENT_SECRET = "***************"
HOST = "127.0.0.1"
PORT = 8000
REDIRECT_URI = f"http://{HOST}:{PORT}/callback"
SCOPES = "restlets rest_webservices"
TOKEN_STORE = "ns_tokens.json"
# ---------- Flask App ----------
app = Flask(__name__)
_auth_code = None
_state = None
_event = threading.Event()
@app.route("/callback")
def callback():
global _auth_code
code = request.args.get("code")
state = request.args.get("state")
if not code or state != _state:
return "Invalid or missing authorization code", 400
_auth_code = code
_event.set()
threading.Thread(target=_shutdown_server).start()
return "<h3>NetSuite authorization successful. You can close this tab.</h3>"
def _shutdown_server():
time.sleep(0.5)
func = request.environ.get("werkzeug.server.shutdown")
if func:
func()
def run_flask():
app.run(host=HOST, port=PORT, debug=False, threaded=True)
# ---------- OAuth Helpers ----------
def build_authorize_url(account_id, state):
base = f"https://{account_id}.app.netsuite.com/app/login/oauth2/authorize.nl"
params = {
"response_type": "code",
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": SCOPES,
"state": state
}
return f"{base}?{urlencode(params)}"
def exchange_code_for_tokens(account_id, code):
token_url = f"https://{account_id}.app.netsuite.com/app/login/oauth2/token.nl"
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI
}
resp = requests.post(token_url, data=data,
auth=(CLIENT_ID, CLIENT_SECRET),
headers={"Content-Type": "application/x-www-form-urlencoded"})
resp.raise_for_status()
return resp.json()
def refresh_access_token(account_id, refresh_token):
token_url = f"https://{account_id}.app.netsuite.com/app/login/oauth2/token.nl"
data = {
"grant_type": "refresh_token",
"refresh_token": refresh_token
}
resp = requests.post(token_url, data=data,
auth=(CLIENT_ID, CLIENT_SECRET),
headers={"Content-Type": "application/x-www-form-urlencoded"})
resp.raise_for_status()
return resp.json()
def save_tokens(obj):
with open(TOKEN_STORE, "w") as f:
json.dump(obj, f)
def load_tokens():
if not os.path.exists(TOKEN_STORE):
return None
with open(TOKEN_STORE, "r") as f:
return json.load(f)
# ---------- MCP Call ----------
def call_mcp(mcp_url, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
return requests.get(mcp_url, headers=headers)
# ---------- Main Flow ----------
def connect_to_mcp(mcp_url):
global _state, _auth_code
# extract account ID from MCP URL
parsed = urlparse(mcp_url)
account_id = parsed.netloc.split(".")[0]
tokens = load_tokens()
access_token = tokens.get("access_token") if tokens else None
refresh_token = tokens.get("refresh_token") if tokens else None
if not access_token:
# Start Flask server
flask_thread = threading.Thread(target=run_flask, daemon=True)
flask_thread.start()
# Start OAuth flow
_state = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(32))
auth_url = build_authorize_url(account_id, _state)
webbrowser.open(auth_url)
if not _event.wait(timeout=300):
raise RuntimeError("Timed out waiting for NetSuite authorization")
tokens = exchange_code_for_tokens(account_id, _auth_code)
save_tokens(tokens)
access_token = tokens["access_token"]
refresh_token = tokens.get("refresh_token")
# Call MCP endpoint
resp = call_mcp(mcp_url, access_token)
if resp.status_code == 401 and refresh_token:
tokens = refresh_access_token(account_id, refresh_token)
save_tokens(tokens)
access_token = tokens["access_token"]
resp = call_mcp(mcp_url, access_token)
if resp.ok:
print("Configured successfully ✅")
else:
print("MCP connection failed:", resp.status_code, resp.text[:500])
# ---------- Entry ----------
if __name__ == "__main__":
MCP_URL = input("Paste your NetSuite MCP URL: ").strip()
connect_to_mcp(MCP_URL)