BOSTON (AP) _ The Massachusetts Supreme Court on Thursday upheld a city of Cambridge regulation banning a defense contractor from testing, storing, transporting and disposing of nerve gas and other warfare chemicals in the community.

The state's highest court voted 4-1 to uphold a Superior Court ruling and declared the ban by the city health commissioner ''valid and enforceable.''

Chief Justice Edward Hennessey said the regulation was ''designed to protect all Cambridge citizens from what the commissioner has concluded is an unacceptable risk.''

Arthur D. Little Inc., a consulting firm, had been testing the chemicals for almost two years under a contract with the U.S. Department of Defense at its Levins Laboratory in Cambridge, a city of 98,000 residents that is home to Harvard University and the Massachusetts Institute of Technology.

In March 1984, Melvin Chalfen, the city health and hospitals commissioner, banned the chemicals from the community.

The company sued, and the ban was stayed pending the Supreme Court ruling.

The majority opinion said the ban is not superceded by the state constitutional grant of war and defense powers to the federal government or by federal legislation that authorizes and regulates chemical warfare research. It also concluded the regulation was not superceded by Arthur D. Little's defense contract.

Alma Triner, a company spokeswoman, said the firm will stop the tests. She did not know if there would be further appeals.

''I think it's fair to say we were surprised and disappointed, but we're going to abide by it,'' said Ms. Triner. ''The volume of work affected by this decision is not really of consequence.''

Scott Lewis, an attorney who represented the city, said, ''We're very happy with the decision but I haven't had a chance to analyze it.''

Justice Neil L. Lynch, who dissented, said the justices applied an outdated test for Chalfen's action that gives an administrative regulation equal weight as a statute, ordinance or bylaw.

''It is unmistakably clear that the commissioner's action is not supported by substantial evidence,'' Lynch also wrote, adding that Chalfen issued his ban before scientific studies were conducted, and that the studies that followed were flawed.

Lynch said the court should ''ensure that administrative bodies act in a manner that is both consistent with statutory policy and reasonably related to life in the real world, rather than some conjectured life in the fictional twilight zone of what is conceivable.''